【问题标题】:Is there a C# syntax for a 'null' lambda expression? eg, calling OrderBy(x => x) without the lambda expression? [duplicate]'null' lambda 表达式是否有 C# 语法?例如,在没有 lambda 表达式的情况下调用 OrderBy(x => x)? [复制]
【发布时间】:2011-09-03 10:59:06
【问题描述】:

可能重复:
LINQ identity function?

为了对整数或字符串之类的东西进行排序而不得不输入x => x 似乎很浪费......有没有更快的方法?

【问题讨论】:

  • 你能展示你的代码来处理这种浪费时间的排序吗?

标签: c# .net linq lambda


【解决方案1】:

如果你有List<T>,你可以使用Sort方法:MyList.Sort(),或者对于其他类型,你可以找到类似的功能。

但是Enumerable.OrderBy MSDN link 说,不,反正没有。

【讨论】:

    【解决方案2】:
    static void Main()
    {
        var array = new[] { 3, 2, 1 };
    
        var result = array.OrderBy(SimpleSort);
    
        foreach (var item in result)
        {
            Console.WriteLine(item);
        }
    }
    
    public static T SimpleSort<T>(T t)
    {
        return t;
    }
    

    或创建自己的扩展:

    public static class Extensions
    {
        public static IEnumerable<TSource> OrderBy<TSource>(this IEnumerable<TSource> source)
        {
            return source.OrderBy(t => t);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2010-11-11
      • 2016-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多