开发者

Fast LINQ query against List<T>

suppose you have an big unsorted List<MyClass> of

public class MyClass
{ 
   public Guid Id { get; set; }
   public string Name开发者_如何学C { get; set; }
}

And I want to search for an item using LINQ. With this simple clause: where my.Id == id. Do you recommend something to get the query faster? IComparable?

Edit: what I mean is I use normal linq or there is a faster option? for example writing a custom IComparable and binarysearch?

Thanks!

Update: I know a Dictionary is the fastest option with a unique ID.


You can just use LINQ's FirstOrDefault:

 MyClass firstMatch = theList.FirstOrDefault(my => my.Id == id);

Without sorting the list, this is probably the best option, even though it's still O(N).


As you stated that your list is unsorted, you can't do anything better than O(n) search, for example using First() or FirstOrDefault() as shown in @Reed Copsey answer.

In fact binary search works only with sorted data, while is useless in other cases.

Anyway, if you need to access several times to that list to find objects using the Id, for sure you will be faster by sorting the list and using binary search (i.e. getting O(log(n)) access time), or by copying the list to a Dictionary<> (i.e. getting ~O(1) access time).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜