December 09, 2016

Linq everything you need to know




·         Linq cheat sheet to print
·         Linq Immediate and Deferred execution (intermediate)

What is it for? What are the benefits? Do I need it?

Reduces code line numbers.
The Linq query can be passed around as a method parameter, it’s not actually run until the developer calls ToList() or something on the query

Linq is not required but it looks good.

Linq and Lambda

Linq is the queryable language, in C# this is implemented as two different types Extension methods (methods like Where() ) or Query Syntax (sql style).

Lambda is the part with the weird => notation known as “to”.
e.g. The complete expression can be known as a Linq query. Made up of a Linq extension method and a Lambda expression.
var allFirstsQuery = data.Where(d => d.Name == “First”);

From Stackoverflow:

This is LINQ (using query syntax):
var _Results = from item in _List
                where item.Value == 1
                select item;
This is also LINQ (using method syntax):
var _Results = _List.Where(x => x.Value == 1);
It's interesting to note that both of these flavors will end up producing the exact same code. The compiler offers you a service by allowing you to express your wishes in the manner that you prefer.
And this is a lambda:
x => x.Value == 1

How to use it

Replacing existing foreachs with linq.

Different types of Linq Methods

LINQ standard query operators (implemented with extension methods in C#) can be categorized into the following ones on the basis of their functionality. Filtering, Join, Projection, Sorting, Grouping, Conversions, Concatenation, Aggregation, Quantifier, Partition, Generation, Set, Equality, Element.


Common examples

More complex examples

Immediate and Delayed execution:

var allFirstsQuery = data.Where(d => d.Name == “First”);
When the runtime get to the line above it does not do anyting except create a variable result.
Only when the result is executed does the query actually run
var allFirstsResultAsList = allFirstsQuery.ToList();
So you could pass allFirstsQuery around as a normal object and execute later. The fact that a query can be created and later executed is important where the target will most likely be different at a later time e.g. the original data object could have a Database StoredProcedure call and the data in there could be different at a later time.

No comments: