Monday, February 6, 2012

LINQ Part 3 - Writing a query

Part 3 - Writing a query 

The quires operate on simple in-memory collections. A user can use any of the following three ways to create a query
  1. Query Syntax
  2.  Method syntax
  3. Combination of query and method syntax
Query Syntax
Query syntax is based on the query keywords which are used to write a query expression. I explained some of the query keywords on my previous post. This helps user to write SQL style commands.
From MSDN, query syntax is the recommended way to write quires. One reason for this is readability factor. Along with that using query syntax we can make use of let and handle complex join operations.

var employeeSalaryQuery = from employee in employees where employee.Salary > 10000

Please note as described in the earlier post, query type is IEnumerable and they do not get executed until they are iterated over a foreach loop.

Method Syntax
Some of the query expressions are wrapped under a method call, i.e as a dot operation. So, if you put a ‘.’ After a list variable, you can find these methods.
Some of these methods returns that return singleton numeric values, such as Sum, Max, Min, Average..etc. Please note these methods will be called last in any query expressions.

List<int> numbers = new List<int>() { 1, 2, 3, 4, 5 };
double average = numbers.Average();

If the methods have parameters, parameters are supplied as lambda expressions. 

var employeeSalaryQuery = employees.Where(e => e.Salary>10000);

Mixed Query
As the name suggest, it contains both query syntax and method syntax. To create mixed queries, enclose query syntax in parenthesis and then call the methods (dot operators).

int employeeCount = (from employee in employees where employee.Salary > 10000).Count();

Previous Post                                        Next Post

No comments:

Featured post

How to connect to Mongo Atlas from Robo 3T

If you use a local instance of MongoDB, you might be a great fan of Robo3T. However, if you are using Mongo Atlas, the Atlas web interface p...

Popular Posts