Can LINQ use binary search when the collection is ordered?

前端 未结 5 798
鱼传尺愫
鱼传尺愫 2020-12-01 02:56

Can I somehow \"instruct\" LINQ to use binary search when the collection that I\'m trying to search is ordered. I\'m using an ObservableCollection, pop

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-01 03:37

    Keep in mind that all(? at least most) of the extension methods used by LINQ are implemented on IQueryableorIEnumerable or IOrderedEnumerable or IOrderedQueryable.

    None of these interfaces supports random access, and therefore none of them can be used for a binary search. One of the benefits of something like LINQ is that you can work with large datasets without having to return the entire dataset from the database. Obviously you can't binary search something if you don't even have all of the data yet.

    But as others have said, there is no reason at all you can't write this extension method for IList or other collection types that support random access.

提交回复
热议问题