Why does List not implement IOrderedEnumerable?

后端 未结 2 743
囚心锁ツ
囚心锁ツ 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 implement IOrderedEnumerable? It would have to provide a way of creating a subsequent ordering... what does that even mean?

    Consider this:

    var names = new List { "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 based on a List - 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 useful.

提交回复
热议问题