Logical difference between LINQ Where() and FirstOrDefault()

c#, linq

Solution

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

Problem

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. 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 } ``` 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.?

Original source

Related problems