linq in plain english

有人可以用简单的英语解释这个语法:

这是OrderBy运算符的签名:

 OrderedSequence OrderBy( this IEnumerable source, Func keySelector ) 

这表明您需要为OrderBy提供的委托类型是Func

我正在寻找一个接收列表和字符串作为参数(列名)的函数,我坚持使用OrderBy扩展方法的语法。 Func是什么意思? 我在哪里放置字符串参数进行排序?

谢谢。

给出了你在实践中如何看待它的方法

 List list; 

 public class MyClass { public string Name { get; set; } // ... } 

你可能会说

 list.OrderBy(x => x.Name); 

this IEnumerable source是我们如何知道我们将其称为任何IEnumerable的扩展方法。

如果您使用动态属性名称,那么您将不得不变得更加花哨。 我首先定义一个辅助函数,以确保我们的lambda不会太乱。 请注意,为了说明概念的时间和清晰度,我省略了一些诸如检查和error handling之类的事情:

 public object GetPropertyByName(object obj, string propertyName) { object result = null; var prop = obj.GetType().GetProperty(propertyName); result = prop.GetValue(obj, null); return result; } 

现在使用我们的助手如下:

 List list = new List(); list.Add(new MyClass { Name = "John" }); list.Add(new MyClass { Name = "David" }); list.Add(new MyClass { Name = "Adam" }); list.Add(new MyClass { Name = "Barry" }); const string desiredProperty = "Name"; // You can pass this in var result = list.OrderBy(x => GetPropertyByName(x, desiredProperty)); foreach (MyClass c in result) { Console.WriteLine(c.Name); } 

好吧,这个人是一个扩展方法(从这个开始),它工作在一些IEnumerable(TElement)上。 它需要一种方法,当给定列表中的元素时,返回可以排序的内容。

来自: http : //msdn.microsoft.com/en-us/library/bb534966.aspx

  class Pet { public string Name { get; set; } public int Age { get; set; } } public static void OrderByEx1() { Pet[] pets = { new Pet { Name="Barley", Age=8 }, new Pet { Name="Boots", Age=4 }, new Pet { Name="Whiskers", Age=1 } }; IEnumerable query = pets.OrderBy(pet => pet.Age); foreach (Pet pet in query) { Console.WriteLine("{0} - {1}", pet.Name, pet.Age); } } /* This code produces the following output: Whiskers - 1 Boots - 4 Barley - 8 */ 

你可以用

 (from o in listOfObjects select o).OrderBy(p => p.columnname) 

此处columnname是您要按其排序的列

Func是指一个函数,它接受TElement类型的参数并返回TKey类型的值。 您可以在调用函数时指定类型(例如foo.OrderBy(...) ),但编译器通常可以从提供的函数中推断它们。

现在, OrderBy不采用列名进行排序,它采用一个函数将对象作为参数进行检查并返回值以进行排序。 例如,

 list.OrderBy(item => item.SortByField) 

当然,除了lambda语法之外,还可以使用其他东西来定义函数(例如,作为常规方法),但这通常是最方便的。

为了按运行时定义的属性名进行排序,您必须想出一种方法来创建一个从指定属性中提取值的函数。 一种方法是使用reflection,另一种方法是使用Expression类动态构造lambda表达式,然后将其编译为Func

这是一个例子(完全未经测试 – 但沿着这些方向的东西)

 using System.ComponentModel; public static IEnumerable OrderByField(this IEnumerable source, string fieldName) { PropertyDescriptor desc = TypeDescriptor.GetProperties(typeof(TValue))[fieldName]; return source.OrderBy(item => desc.GetValue(item)); }