Monday, January 18, 2016

LINQ Syntex

LINQ Syntax

There are two basic ways to write a LINQ query:
  1. Query Syntax or Query Expression Syntax
  2. Method Syntax or Method extension syntax or Fluent

Query Syntax:

Query syntax is similar to SQL (Structured Query Language) for a database. It is defined within the C# or VB code.
from <range variable> in <collection>
<filter, joining, grouping, aggregate operators etc.> <lambda expression>
<select or groupBy operator> <formulate the result>

Example
int[] numbs = new int[7] { 0, 1, 2, 3, 4, 5, 6 };
var numQry = from num in numbs
             where (num % 2) == 0
             select num;

Query Syntax starts with from clause followed by Range variable. After from clause, you can use different standard query operations such as filter, group, joins etc. there are 50 standard query operators available in LINQ. In Above Example we used where operator to filter even numbers. LINQ always ends with select or group by clause. The select is used to get data from source. You can have whole object or some properties of the object in select section.


LINQ Method Syntax

Method syntax (also known as fluent syntax) uses extension methods included in the Enumerable or Queryable static class, similar to how you would call the extension method of any class.
The following figure illustrates the structure of LINQ method syntax.

Example
IList<Student> studentList = new List<Student>() {
    new Student() { StudentID = 1, StudentName = "John", Age = 13} ,
    new Student() { StudentID = 2, StudentName = "Moin",  Age = 21 } ,
    new Student() { StudentID = 3, StudentName = "Bill",  Age = 18 } ,
    new Student() { StudentID = 4, StudentName = "Ram" , Age = 20} ,
    new Student() { StudentID = 5, StudentName = "Ron" , Age = 15 }
};

// LINQ Method Syntax to find out teenager students
var teenAgerStudents = studentList.Where(s => s.Age > 12 && s.Age < 20)
                                  .ToList<Student>();


As you can see in the above figure, method syntax comprises of extension methods and Lambda expression. The extension methods Where and ToList are defined in the Enumerable class.

No comments:

Post a Comment