1

I have a doubt

If I have two approaches like

int a = (from e in MyIntegerList where e % 2 == 0 select e).FirstOrDefault();

and

int a = MyIntegerList.FirstOrDefault(e => e % 2 == 0);

Which will be more efficent and why?

I heard that FirstOrDefault(with predicate) will not iterate on whole collection and will return first element that matches the condition?

Will that be the case with both statements above or not?

Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
  • 1
    The first statement will be transformed into `.Where(your condition).FirstOrDefault()` by the compiler, so it creates a full Enumerable fulfilling your condition and then pick the first, while the second statement picks the first element fulfilling the condition, without iterating through the complete array. – LInsoDeTeh Jul 15 '15 at 09:14
  • 1
    None of these will scan the whole list. The first matching item will be returned as soon as found in both cases. – vc 74 Jul 15 '15 at 09:15
  • @Tim Schmelter: Is what `LInsoDeTeh` saying above correct or not. – Nikhil Agrawal Jul 15 '15 at 09:17
  • @vc74: Can you prove that by providing some link or something. – Nikhil Agrawal Jul 15 '15 at 09:17
  • @NikhilAgrawal: it's not quite correct what he says but that might be a language issue. Basically both approaches are same, both stop on the first item that matches the given condition and return that. But your mixing of query and method syntax is confusing. The first aproach is the same as: `MyIntegerList.Where(e => e % 2 == 0).FirstOrDefault()` – Tim Schmelter Jul 15 '15 at 09:19
  • I was wrong, sorry. I was looking from a pure object-oriented perspective but forgot that LINQ statements are evaluated on-demand. Even though the compiler changes the query to an extension method call, it will not loop the whole array. It's explained well in the 'possible duplicate' topic linked by Tim. – LInsoDeTeh Jul 15 '15 at 09:21
  • namespace ConsoleApplication1 { class Program { static void Main(string[] args) { int firstEven1 = (from e in GetInts() where e % 2 == 0 select e).FirstOrDefault(); Console.WriteLine(firstEven1); int firstEven2 = GetInts().FirstOrDefault(e => e % 2 == 0); Console.WriteLine(firstEven2); } private static IEnumerable GetInts() { Console.WriteLine("About to return 1"); yield return 1; Console.WriteLine("About to return 2"); yield return 2; Console.WriteLine("About to return 3"); yield return 3; } } } – vc 74 Jul 15 '15 at 09:24
  • @NikhilAgrawal sorry about the format of my 'answer' but your question has been marked as a duplicate so I can't post an answer. Try to execute this console app, you'll not see About to return 3 in any case. – vc 74 Jul 15 '15 at 09:26
  • @vc74: No problem bro. Thanks for the help. :) – Nikhil Agrawal Jul 15 '15 at 09:41
  • @LInsoDeTeh: You can remove your comments. No problem bro. Thanks for the help. – Nikhil Agrawal Jul 15 '15 at 09:42

0 Answers0