Understanding LINQ’s Shift from Imperative to Declarative Program
Learn about LINQ expressions, LINQ’s declarative approach streamlines tasks and improves code efficiency.
The first question we need to answer is fundamental: why LINQ?
Comparing imperative and declarative language features
LINQ was introduced in 2008 with C# 3.0 and .NET Framework 3.0. Before that, if a C# and .NET programmer wanted to process a sequence of items, they had to use procedural, also known as 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 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 to the next item. Repeat until all items have been processed.
The power of imperative code
Procedural, also known as imperative, code tells the compiler how to achieve a goal. Do this. Then do that. Since the compiler does not know what we are trying to achieve, it cannot help us as much. We are 100% responsible for ensuring that every how-to step is exactly correct.
Get hands-on with 1400+ tech skills courses.