Concept of LINQ with C#

LINQ stands for Language Integrated Query. LINQ is a data querying API that provides querying capabilities to .NET languages with a syntax similar to a SQL. LINQ queries use C# collections to return data.

LINQ stands for Language Integrated Query. LINQ is a data querying API with SQL like query syntaxes. LINQ provides functions to query cached data from all kinds of data sources. The data source could be a collection of objects, database or XML files. We can easily retrieve data from any object that implements the IEnumerable<T> interface.
 
The official goal of the LINQ family of technologies is to add "general purpose query facilities to the .NET Framework that apply to all sources of information, not just relational or XML data".
 
20-11.jpg 
 
Advantages of LINQ
  1. LINQ offers an object-based, language-integrated way to query over data no matter where that data came from. So through  LINQ we can query database, XML as well as collections. 
  2. Compile time syntax checking
  3. It allows you to query collections like arrays, enumerable classes etc in the native language of your application, like VB or C# in much the same way as you would query a database using SQL
LINQ to Object
 
LINQ to Object provides functionality to query in-memory objects and collections. Any class that implements the IEnumerable<T> interface (in the System.Collections.Generic namespace) can be queried with SQO.
 
LINQ to ADO.NET
 
LINQ to ADO.NET deals with data from external sources, basically anything ADO.NET can connect to. Any class that implements IEnumerable<T> or IQueryable<T> (in the System.Query namespace) can be queried with SQO.  
  • LINQ to SQL (DLinq) {Queries performed against the relation database only Microsoft SQL Server Supported} 
  • LINQ to DataSet {Supports queries by using ADO.NET data sets and data tables} 
  • LINQ to Entities 
LINQ to XML (XLinq)
 
LINQ to XML is used to query XML data sources.
 
Here is a detailed tutorial on LINQ with C# for beginners. 
 
LINQ Code Examples
 
Here is a simple example that creates a array of integers. A LINQ query is used to return a var that stores the collection of returned data. Learn more: The var keyword in C#.
  1. int[] nums = new int[] {0,1,2};  
  2. var res = from a in nums where a < 3 orderby a select a;  
  3. foreach(int i in res)   
  4.  Console.WriteLine(i);
Let's look at a working example. Create a Web page or UI with a GridView control that we will use to display some data. The following code example defines a class, patient with some properties such as name, gender, age, and area.
  1. public class patient  
  2. {  
  3.       public patient()  
  4.        {  
  5.        }  
  6.        // Fields  
  7.         private string _name;  
  8.         private int _age;  
  9.         private string _gender;  
  10.         private string _area;  
  11.         // Properties  
  12.         public string PatientName  
  13.         {  
  14.             get { return _name; }  
  15.             set { _name = value; }  
  16.        }  
  17.          public string Area  
  18.         {  
  19.             get { return _area; }  
  20.             set { _area = value; }  
  21.         }  
  22.         public String Gender  
  23.         {  
  24.             get { return _gender; }  
  25.             set { _gender = value; }  
  26.         }  
  27.         public int Age  
  28.         {  
  29.             get { return _age; }  
  30.             set { _age = value; }  
  31.         }  
  32. }
Now, on the Web Page (ASP.NET Web Forms in this case), we create a List object dynamically. This program adds a single record but you an add a collection of records. Once the collection is ready, LINQ can be used to query the collection. 
 
In this code, a recorded is queired using LINQ and displayed in a GridView control.
 
Main Program
  1. using System.Collections.Generic;  
  2. public partial class _Default : System.Web.UI.Page   
  3. {  
  4.     protected void Page_Load(object sender, EventArgs e)  
  5.     {  
  6.         List<patient> pat=new List<patient>();  
  7.         patient p=new patient();  
  8.         p.patientname="Deepak dwij";  
  9.         p.patientstate = "UP";  
  10.         p.patientage = "25";  
  11.         p.patientcity = "Noida";  
  12.         pat.Add(p);  
  13.         GridView1.DataSource = from a in pat select a;  
  14.         GridView1.DataBind();    
  15.         //GridView1.DataSource = from pa in patients  
  16.                                    //where pa.Gender == "Male"  
  17.                                    //orderby pa.PatientName, pa.Gender, pa.Age  
  18.                                    //select pa;  
  19.         //GridView1.DataBind();       
  20.     }  
  21. }
The following code uses the selection operator type, which brings all those records whose age is more than 20 years.
  1. var mypatient = from pa in patients  
  2.                   where pa.Age > 20  
  3.                   orderby pa.PatientName, pa.Gender, pa.Age  
  4.                   select pa;  
  5.         foreach(var pp in mypatient)  
  6.         {  
  7.         Debug.WriteLine(pp.PatientName + " "+ pp.Age + " " + pp.Gender);  
  8.         }   
The following code snippet uses the grouping operator type that group patient data on the bases area.
  1. var op = from pa in patients  
  2.             group pa by pa.Area into g  
  3.             select new {area = g.Key, count = g.Count(), allpatient = g};  
  4.     foreach(var g in op)  
  5.      {  
  6.       Debug.WriteLine(g.count+ "," + g.area);  
  7.        foreach(var l in g.allpatient)  
  8.         {  
  9.          Debug.WriteLine("\t"+l.PatientName);  
  10.         }  
  11.      }  
  1. int patientCount = (from pa in patients  
  2.                     where pa.Age > 20  
  3.                     orderby pa.PatientName, pa.Gender, pa.Age   
  4.                    select pa).Count();  
Linq Example

Simple select

  1. int[] numbers = { 5, 4, 1, 3, 9, 8};  
  2. var numsPlusOne =from n in numbers select n;  
  3. foreach (var i in numsPlusOne)  
  4. {  
  5.     MessageBox.Show(i.ToString() );  
  6. }  
Multiple select
  1. int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };  
  2. int[] numbersB = { 1, 3, 5, 7, 8 };  
  3. var pairs =from a in numbersA from b in numbersB where a < b select new { a, b };  
  4. Console.WriteLine("Pairs where a < b:");  
  5. foreach (var pair in pairs)  
  6. {  
  7.     Console.WriteLine("{0} is less than {1}", pair.a, pair.b);  
  8. }  
Order by
  1. string[] words = { "cherry""apple""blueberry" };  
  2. var sortedWords =from w in words orderby w select w;  
  3. Console.WriteLine("The sorted list of words:");  
  4. foreach (var w in sortedWords)  
  5. {  
  6.     Console.WriteLine(w);  
  7. }  
Count function
  1. int[] factorsOf300 = { 2, 2, 3, 5, 5 };  
  2. int uniqueFactors = factorsOf300.Distinct().Count();  
  3. Console.WriteLine("There are {0} unique factors of 300.", uniqueFactors);  
OR
  1. int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
  2. int oddNumbers = numbers.Count(n => n % 2 == 1);
  3. Console.WriteLine("There are {0} odd numbers in the list.", oddNumbers);
Want more LINQ? Here is another tutorial LINQ for Beginners