Why does List not implement IOrderedEnumerable?

后端 未结 2 791
囚心锁ツ
囚心锁ツ 2021-02-19 19:54

I would like to work with ordered enumerables, and use interfaces as return types rather than the concrete types. I need to return an ordered set of objects. Bu

相关标签:
2条回答
  • 2021-02-19 20:22

    How could List<T> implement IOrderedEnumerable<T>? It would have to provide a way of creating a subsequent ordering... what does that even mean?

    Consider this:

    var names = new List<string> { "Jon", "Holly", "Tom", "Robin", "William" };
    var ordered = names.ThenBy(x => x.Length);
    

    what does that even mean? There's no primary sort order (as there would be if I used names.OrderBy(x => x)), so it's impossible to impose a secondary sort order.

    I suggest you try creating your own implementation of IOrderedEnumerable<T> based on a List<T> - as you attempt to implement the CreateOrderedEnumerable method, I think you'll see why it's inappropriate. You may find my Edulinq blog post on IOrderedEnumerable<T> useful.

    0 讨论(0)
  • 2021-02-19 20:26

    Well, you are wrong: List<T> is NOT ordered by a particular key. The elements inside the list are in the order you put them in. That's the reason, why List<T> doesn't implement IOrderedEnumerable<T>.
    Just return the following:

    ViewModel.SeriesRepository.OfType<T>().OrderBy(<your order predicate>);
    
    0 讨论(0)
提交回复
热议问题