简体   繁体   中英

Does where clause in LINQ perform binarysearch or linearsearch

So, when we have a list of integers / string / object and try to search an element in that list using LINQ.

Does LINQ perform binarysearch or linearsearch internally?

public class Person
{
    public string Name { get; set; }
    public string Address { get; set; }
}

and our LINQ, looks something like this:

List<Person> persons = new List<Person>();
persons.Where(x => x.Name == "kushal");

Where is not a search for a single element. It's just a way to allow executing your predicate (a function that returns true or false) on each element and return elements where the predicate is true.

In order to move through the collection LINQ uses iterators so the movement depends on the iterator. List<T> has a dedicated iterator for Where . You can see this in .NET sources: public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) :

...
if (source is List<TSource> list)
{
   return new WhereListIterator<TSource>(list, predicate);
}

WhereListIterator 's MoveNext in turn uses List's MoveNext and List<T> 's MoveNext moves one item at a time in the following fashion:

_current = localList._items[_index];
_index++;

When you reason about this it's worth remembering that LINQ doesn't actually move through the list. Only when you enumerate the result of .Where - for example with foreach or ToList - the real work is done (moving through the elements and checking if the predicate is true).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM