LINQ is a set of technologies that allow simple and efficient querying over different kinds of data. It allows filtering, ordering and transforming the collection elements, and more.
LINQ can work with other types of collections like databases or XML files and syntax remains the same.
Most of the LINQ methods are extension methods for IEnumerable<T>, that means we can use them with any type that implements IEnumrable<T> interface. Another thing to note about IEnumrable<T> is that it doesn’t expose any method for collection modification. When you see some method such as Append, the collection object will not be modifed. A new collection will be created instead.
Deferred Execution
Deferred execution means that the evaluation of a LINQ expression is delayed until the value is actually needed. It improves performance by avoiding unnecessary execution.
var words = new List<string> { "a", "bb", "ccc", "dddd" };
var shortWords = words.Where(w => w.Length < 3);
Console.WriteLine("First iteration");
foreach(var word in shortWords)
{
Console.WriteLine(word); // will print a,bb
}
words.Add("e");
Console.WriteLine("Second iteration");
foreach(var word in shortWords)
{
Console.WriteLine(word); // will print a,bb,e
}LINQ defines querys to retrive data. We can force the materialization of data by, for example, using the ToList method. In the above code, if we say var shortWords = words.Where(w => w.Length < 3).ToList(), then shortWords will be a list, not a query, and the 2 printed results will be the same.
Any
Check if ANY element in the colletion matches the given criteria. It will take a function predicate as parameter, so we can pass a lambda here. We can also skip the parameter of the Any method to simply check if the collection is not empty. E.g.. bool isNotEmpty= someCollection.Any(). It will return true if collection is NOT empty.
All
check if ALL elements in the collction mathcing the given criteria.
