Writing LINQ expressions
The first question we need to answer is a fundamental one: Why does LINQ exist?
Comparing imperative and declarative language features
LINQ was introduced in 2008 with C# 3 and .NET Framework 3. Before that, if a C# and .NET programmer wanted to process a sequence of items, they had to use procedural, aka imperative, code statements. For example, a loop:
- Set the current position to the first item.
- Check if the item is one that should be processed by comparing one or more properties against specified values. For example, is the unit price greater than 50, or is the country equal to Belgium?
- If there’s a match, process that item. For example, output one or more of its properties to the user, update one or more properties to new values, delete the item, or perform an aggregate calculation, like counting or summing values.
- Move on to the next item. Repeat until all items have been processed.
Procedural code...