Junior (0-2 years)C#

What is LINQ in C# and what is deferred execution?

Quick answer

LINQ (Language Integrated Query) lets you query collections, databases and XML with a consistent syntax, and deferred execution means a query does not run when you define it but when you enumerate the results.

Methods such as Where, Select and OrderBy only build up a description of the query. The work happens when you iterate with foreach or call an operator that forces evaluation, such as ToList(), ToArray(), Count() or First().

This is efficient, but it has traps: if the source changes between defining and enumerating the query, you see the new data, and enumerating the same query twice runs it twice (a database query would hit the database twice). Call ToList() when you want a snapshot or need to reuse the results.

var numbers = new List<int> { 1, 2, 3 };
var evens = numbers.Where(n => n % 2 == 0);   // nothing runs yet

numbers.Add(4);
Console.WriteLine(string.Join(",", evens));   // 2,4  (runs now)

var snapshot = numbers.Where(n => n > 1).ToList();   // runs immediately