Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logical difference between LINQ Where() and FirstOrDefault()

Tags:

c#

linq

I know this may sound duplicate question (like this or this ) but I wanted some clarity regarding the number iterations that will take place in this query.

My assumptions are as follows:

lets say I have collection of 1000 items.

  1. In Where() query, it iterates through each and every item and add it to IEnumerable. i.e. it will need O(n) always.

    foreach (var item in myList)
    {
        if(//<condition>)
        {
            //add it to list/enumerable
        }
        //continue through entire list
    }
    
  2. In FirstOrDefault(<condition>) query,it starts iterating through the collection and breaks the loop as soon as it gets the item matching the <condition> and returns single element or only if no item is matching <condition> then it will iterate through entire list.

so complexity can be from O(1) to O(n)

foreach (var item in myList)
{
    if(//<condition>)
    {
        //return item
        break;
    }
}

if this is correct then it will always be better to use FirstORDefault for a single item return.?

like image 241
deathrace Avatar asked Nov 18 '13 15:11

deathrace


2 Answers

Where is actually deferred - i.e. it does not have any cost until the enumeration happens.

Where looks kind of like this, and returns a new IEnumerable<T>.

foreach (var item in enumerable)
{
    if (condition)
    {
        yield return item;
    }
}

FirstOrDefault returns T.

like image 196
Daniel A. White Avatar answered Oct 29 '22 05:10

Daniel A. White


FirstOrDefault will stop checking (i.e. break) when/if it finds anything.

edit: However, as Daniel pointed out, Where is deferred, so you can also stop iterating yourself and it will have the same performance as FirstOrDefault (although then you might as well just use FirstOrDefault)

like image 32
David S. Avatar answered Oct 29 '22 06:10

David S.