How to make this more generic
[code]
private static IOrderedEnumerable<Film> OrderBy(this IEnumerable<Film> source, Func<Film, object> order, bool desc)
{
if (desc) { return source.OrderByDescending(order); }
return source.OrderBy(order);
}
[Situation]
Ofcourse, linq already implements a order by. I'm only trying to generize it more. Mostly just to learn things, it doesn't really add things other then that I can order by normally or order by descending with the same property.
[Question]
However I wish to make it more generic. Currently it only takes IEnumerable<T> and return IOrderedEnumerable<T> (where T currently is a movie. Custom model). Is there any general type of list, enumerable or something that covers all 开发者_运维百科List, IEnumerable IOrderedEnumerable etcetc?
Yes, there is. It's IEnumerable<T>
.
Classes like List<T>
implement the IEnumerable<T>
interface, so a method that takes IEnumerable<T>
can be used with most any collection.
You forgot to specify the generic parameter to the method: OrderBy<Film>
.
The original OrderBy
method also have a generic parameter for the type of the key. You might also want to use that, to make sure that the comparisons work properly, and that it doesn't do a lot of unnecessary boxing and unboxing:
private static IOrderedEnumerable<Film> OrderBy<Film, Key>(this IEnumerable<Film> source, Func<Film, Key> order, bool desc) {
if (desc) { return source.OrderByDescending(order); }
return source.OrderBy(order);
}
精彩评论