I understand the above doesn't work but i haven't anyidea what i should be putting in the brackets.
The declaration of Enumerable.OrderBy
is
public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector
)
and, as it's an extension method it can be invoked as
source.OrderBy(keySelector).
Your List<Car>
is playing the role of source
as List<T> : IEnumerable<T>
. The second parameter is the more interesting one and the one that you are confused by. It's declared as being of type
Func<TSource, TKey>
This means that it is a delegate that eats instances of TSource
(in your case Car
) and returns an instance of TKey
; it's up to you to decide what TKey
is. You have stated that you want to order by Car.registrationDate
so it sounds like TKey
is DateTime
. Now, how do we get one of these delegates?
In the old days we could say
DateTime GetRegistrationDate(Car car) {
return car.registrationDate;
}
and use OrderBy
like so:
allCars.OrderBy(GetRegistrationDate).
In C# 2.0 we gained the ability to use anonymous delegates; these are delegates that don't have a name and are defined in-place.
allCars.OrderBy(delegate(Car car) { return car.registrationDate; });
Then, in C# 3.0 we gained the ability to use lambda expressions which are very special anonymous delegates with a compact notation
allCars.OrderBy(car => car.registrationDate);
Here, c => c.registrationDate
is the lambda expression and it represents a Func<Car, DateTime>
than can be used the second parameter in Enumerable.OrderBy
.
allCars.orderBy(registrationDate)
The reason this doesn't work is because registrationDate
is not a delegate. In fact, without any context at all registrationDate
is meaningless to the compiler. It doesn't know if you mean Car.registrationDate
or maybe you mean ConferenceAttendee.registrationDate
or who knows what. This is why you must give additional context to the compiler and tell it that you want the property Car.registrationDate
. To do this, you use a delegate in one of the three ways mentioned above.