C# Linq Where(expression).FirstorDefault() vs .FirstOrDefault(expression)

C#Linq

C# Problem Overview


What is the difference between these two Linq queries:

var result = ResultLists().Where( c=> c.code == "abc").FirstOrDefault();
// vs.
var result = ResultLists().FirstOrDefault( c => c.code == "abc");
  • Are the semantics exactly the same?

  • Iff sematically equal, does the predicate form of FirstOrDefault offer any theoretical or practical performance benefit over Where() plus plain FirstOrDefault()?

C# Solutions


Solution 1 - C#

Either is fine.

They both run lazily - if the source list has a million items, but the tenth item matches then both will only iterate 10 items from the source.

Performance should be almost identical and any difference would be totally insignificant.

Solution 2 - C#

The second one. All other things being equal, the iterator in the second case can stop as soon as it finds a match, where the first one must find all that match, and then pick the first of those.

Solution 3 - C#

Nice discussion, all the above answers are correct.

I didn't run any performance test, whereas on the bases of my experience FirstOrDefault() sometimes faster and optimize as compare to Where().FirstOrDefault().

I recently fixed the memory overflow/performance issue ("neural-network algorithm") and fix was changing Where(x->...).FirstOrDefault() to simply FirstOrDefault(x->..).

I was ignoring the editor's recommendation to change Where(x->...).FirstOrDefault() to simply FirstOrDefault(x->..).

So I believe the correct answer to the above question is

The second option is the best approach in all cases

Solution 4 - C#

Where is actually a deferred execution - it means, the evaluation of an expression is delayed until its realized value is actually required. It greatly improves performance by avoiding unnecessary execution.

Where looks kind of like this, and returns a new IEnumerable

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

FirstOrDefault() returns <T> and not throw any exception or return null when there is no result

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSOFextremeView Question on Stackoverflow
Solution 1 - C#EnigmativityView Answer on Stackoverflow
Solution 2 - C#Dave CView Answer on Stackoverflow
Solution 3 - C#Ihtsham MinhasView Answer on Stackoverflow
Solution 4 - C#Akhilesh KamateView Answer on Stackoverflow