LINQ Feature in C#

LINQ- Language-Integrated Query-

LINQ provides a common syntax for querying any type of data source. LINQ is collection of extensions to the .Net Framework 3.0 and its managed languages that set the query as an object. It defines a common syntax and a programming model to complex query operations against any enumerable object.

Query expressions use a whole new set of keywords Sorting, Skip, SkipWhile ,Take, TakeWhile and the relational operators like Join, Group, Select, Project, , Partition, Set operations etc., are implemented in LINQ and the C# compilers in the .Net framework 3.0, which support the LINQ syntax and makes it possible to work with a configured data store without using data sources query.

There are following assemblies used,

  • using System.Linq -This is main assembly for Linq query on collections
  • using System.Collections.Generic- this is used for linq to object
  • using System.Data.Linq- This is for Linq to Sql
  • using Sytem.Xml.Linq.Mapping – this is Designates a class as an entity associated with a database.

Query expression is used two types-

LINQ Operators

LINQ defines a set of standard query operators that allow traversal, filter, and projection operations to be expressed directly in any .NET-based language.

Basic Operators is used “From ,Where, in,select”.

Ex.

  1. int[] array = { 1, 2, 3, 6, 7, 8 };  
  2.   
  3. // Query expression.  
  4.   
  5. var elements = from element in array  
  6.   
  7. orderby element descending  
  8.   
  9. where element > 2  
  10.   
  11. select element;  
  12.   
  13. // Enumerate  
  14.   
  15. Response.Write(string.Format("-------------"));  
  16.   
  17. foreach (var element in elements)  
  18.   
  19. {  
  20.   
  21. Response.Write(string.Format("{0} </br>", element));  
  22.   
  23. }  


Lamda expression

Lamda expression was introduced in C# 3.0. Basically, Lamda expression is a more concise syntax of anonymous methods. It is just a new way to write anonymous methods. At compile time all the lamda expressions are converted into anonymous methods according to lamda expression conversion rules.The left side of the lamda operator "=>" represents the arguments to the method and the right side is the method body.

These expressions are expressed by the following syntax:

(input parameters) => expression or statement block

Lambda expressions themselves do not have type.

A lambda expression cannot be assigned to an implicitly typed local variable since the lambda expressions do not have type.

Ex.

  1. List<int> numbers = new List<int> { 11, 37, 52,9,10,5,10,6 };  
  2.   
  3. List<int> oddNumbers = numbers.Where(n => n % 2 == 1).ToList();  
  4.   
  5. foreach (int i in oddNumbers)  
  6.   
  7. {  
  8.   
  9. Response.Write(string.Format("{0} </br>", i));  
  10.   
  11. }  

Next Recommended Reading C# LINQ Joins With Query Structure