如何使这个更通用
[代码]
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);
}
[情况]
当然,linq 已经实现了 order by。我只是想更通用化它。主要只是为了学习东西,除了我可以正常排序或按相同属性降序排序之外,它并没有真正添加其他东西。
[问题]
但是我希望使其更通用。目前只需要 IEnumerable
[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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,有。它是
IEnumerable
。List
等类实现IEnumerable
接口,因此采用IEnumerable
的方法可以与大多数收藏。您忘记为该方法指定通用参数:
OrderBy
。原始的
OrderBy
方法还有一个键类型的通用参数。您可能还想使用它来确保比较正常工作,并且它不会进行大量不必要的装箱和拆箱:Yes, there is. It's
IEnumerable<T>
.Classes like
List<T>
implement theIEnumerable<T>
interface, so a method that takesIEnumerable<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: