我有一个问题,我允许用户选择criterea订购列表列表<T>订购
比方说我的列表被称为
List<Cars> AllCars = new List<Cars>;
allCars = //call the database and get all the cars
我现在想订这个名单
allCars.orderBy(registrationDate)
我明白上述不起作用,但我没有anyidea我应该放在括号内。
我有一个问题,我允许用户选择criterea订购列表列表<T>订购
比方说我的列表被称为
List<Cars> AllCars = new List<Cars>;
allCars = //call the database and get all the cars
我现在想订这个名单
allCars.orderBy(registrationDate)
我明白上述不起作用,但我没有anyidea我应该放在括号内。
allCars.OrderBy(c => c.RegistrationDate);
我理解以上不工作,但我还没有anyidea我应该在括号内投入。
的Enumerable.OrderBy
的声明是
public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector
)
和,因为它是一个扩展方法可以援引作为
source.OrderBy(keySelector).
你List<Car>
是扮演List<T> : IEnumerable<T>
的source
作用。第二个参数是更有趣的一个,你被困惑的那个。它的声明为类型的
Func<TSource, TKey>
这意味着它是吃的TSource
情况下(在你的情况Car
)的委托,并返回TKey
实例;这取决于你决定什么TKey
。您已经声明您要订购Car.registrationDate
,因此听起来像TKey
是DateTime
。现在,我们如何获得这些代表中的一个?
在旧时代,我们可以说
DateTime GetRegistrationDate(Car car) {
return car.registrationDate;
}
,并使用OrderBy
像这样:
allCars.OrderBy(GetRegistrationDate).
在C#2.0中,我们获得了使用匿名委托的能力;这些代表是没有名称并在原地定义的代表。
allCars.OrderBy(delegate(Car car) { return car.registrationDate; });
然后,在C#3.0,我们得到了使用lambda表达式,这是非常特殊的匿名委托具有结构紧凑符号
allCars.OrderBy(car => car.registrationDate);
这里的能力,c => c.registrationDate
是lambda表达式,它代表了Func<Car, DateTime>
比可以使用Enumerable.OrderBy
中的第二个参数。
allCars.orderBy(registrationDate)
这不工作的原因是因为registrationDate
不是委托。实际上,没有任何上下文,编译器对编译器毫无意义。它不知道你的意思是Car.registrationDate
或者你的意思是ConferenceAttendee.registrationDate
或谁知道什么。这就是为什么你必须给编译器提供额外的上下文,并告诉它你想要属性Car.registrationDate
。为此,您使用上述三种方法之一使用委托。
感谢您的解释我想我会做一些更多的研究,以他们似乎看起来挺直的兰达达表达式 – Truezplaya 2010-01-31 15:23:37
你说得对,'兰达达'的表情听起来很有趣;) – Benjol 2010-02-01 10:53:38
感谢您的快速回复,但它不起作用c => c。给我等于,getHash,toString和其他东西 – Truezplaya 2010-01-31 15:03:28
allCars必须是“T”类型,“registrationDate”必须是这个类型字段。 – Restuta 2010-01-31 15:10:51
由于allCars是'Cars'的列表,因此'Cars'类型必须具有公共RegistrationDate属性或字段才能orderby。 – 2010-01-31 15:17:29