elranu
elranu

Reputation: 2312

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 { 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.

Upvotes: 0

Views: 2371

Answers (2)

digEmAll
digEmAll

Reputation: 57210

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).

Upvotes: 2

Reed Copsey
Reed Copsey

Reputation: 564383

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).

Upvotes: 12

Related Questions