我有一個問題,我允許用戶選擇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