There are two basic ways to write a LINQ query to IEnumerable collection or IQueryable data sources.
- Query Syntax - aka Query Expression Syntax
- This is similar to SQL (Structured Query Language) for the database.
- The LINQ query starts with the From clause and ends with the Select or GroupBy clause.
- Implicitly typed variable - var can be used to hold the result of the LINQ query.
- You can use various query operators (filtering, joining, grouping. sorting etc.) to construct the desired result.
- Method Syntax - aka Method extension syntax or Fluent
- Uses extension method included in the Enumerable and Queryable static class.
- Method syntax comprises of extension methods and Lamda expressions.
- Implicitly typed variable - var can be used to hold the result of the LINQ query.
Lamda Expressions - A shorter way of representing anonymous methods using special syntax. In the above example.
- Syntax: parameter => body expression
In below example i is the parameter , => is the Lamda operator, and (i%2) == 0 is the body expression.
- Can have zero parameters.
- Can have multiple parameters.
- Can have multiple statements in body expression.
- Can be assigned to generic delegates Func, Acton or Predicate.
- Can be invoked same way as delegate.
No comments:
Post a Comment