Concept of LINQ with C#


Introduction

LINQ

LINQ stands for Language Integrated Query. LINQ is a data querying methodology which provides querying capabilities to .NET languages with a syntax similar to a SQL query

LINQ has a great power of querying on any source of data. The data source could be collections of objects, database or XML files. We can easily retrieve data from any object that implements the IEnumerable<T> interface. Microsoft basically divides LINQ into three areas and that are give below.

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 {Queries performed against the in-memory data} 


LINQ to ADO.NET

  • 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) { Queries performed against the XML source}

LINQ to Objects deals with in-memory data. Any class that implements the IEnumerable<T> interface (in the System.Collections.Generic namespace) can be queried with SQO.

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.

e.g.
         
int[] nums = new int[] {0,1,2};
          var res = from a in nums where a < 3 orderby a select a;
          foreach(int i in res)
           Console.WriteLine(i);

e.g.  ASP.NET

Class

public class patient
{
      public patient()
       {
       }
           // Fields
        private string _name;
        private int _age;
        private string _gender;
       private string _area;
        // Properties
        public string PatientName
        {
            get { return _name; }
            set { _name = value; }
       }
         public string Area
        {
            get { return _area; }
            set { _area = value; }
        }
        public String Gender
        {
            get { return _gender; }
            set { _gender = value; }
        }
        public int Age
        {
            get { return _age; }
            set { _age = value; }
        }
}

Main Program

using System.Collections.Generic;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        List<patient> pat=new List<patient>();
        patient p=new patient();
        p.patientname="Deepak dwij";
        p.patientstate = "UP";
        p.patientage = "25";
        p.patientcity = "Noida";
        pat.Add(p);
        GridView1.DataSource = from a in pat select a;
        GridView1.DataBind(); 
        //GridView1.DataSource = from pa in patients
                                   where pa.Gender == "Male"
                                   orderby pa.PatientName, pa.Gender, pa.Age
                                   select pa;
        //GridView1.DataBind();    
    }
}

e.g.

The following code uses the selection operator type, which brings all those records whose age is more than 20 years.

var mypatient = from pa in patients
                  where pa.Age > 20
                  orderby pa.PatientName, pa.Gender, pa.Age
                  select pa;
        foreach(var pp in mypatient)
        {
        Debug.WriteLine(pp.PatientName + " "+ pp.Age + " " + pp.Gender);
        }
e.g.

The following code snippet uses the grouping operator type that group patient data on the bases area.

var op = from pa in patients
            group pa by pa.Area into g
            select new {area = g.Key, count = g.Count(), allpatient = g};
    foreach(var g in op)
     {
      Debug.WriteLine(g.count+ "," + g.area);
       foreach(var l in g.allpatient)
        {
         Debug.WriteLine("\t"+l.PatientName);
        }
     }

e.g.

int patientCount = (from pa in patients
                    where pa.Age > 20
                    orderby pa.PatientName, pa.Gender, pa.Age
                   select pa).Count();

Linq Example

Simple select
   
  
    int[] numbers = { 5, 4, 1, 3, 9, 8};
            var numsPlusOne =from n in numbers select n;
            foreach (var i in numsPlusOne)
            {
                MessageBox.Show(i.ToString() );
            }
Multiple select

    
int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };
    int[] numbersB = { 1, 3, 5, 7, 8 };
    var pairs =from a in numbersA from b in numbersB where a < b select new { a, b };
    Console.WriteLine("Pairs where a < b:");
    foreach (var pair in pairs)
    {
        Console.WriteLine("{0} is less than {1}", pair.a, pair.b);
    }

Order by

   
string[] words = { "cherry", "apple", "blueberry" };
    var sortedWords =from w in words orderby w select w;
    Console.WriteLine("The sorted list of words:");
    foreach (var w in sortedWords)
    {
        Console.WriteLine(w);
    }

Count function

  
int[] factorsOf300 = { 2, 2, 3, 5, 5 };
  int uniqueFactors = factorsOf300.Distinct().Count();
   Console.WriteLine("There are {0} unique factors of 300.", uniqueFactors);

OR

 
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
  int oddNumbers = numbers.Count(n => n % 2 == 1);
   Console.WriteLine("There are {0} odd numbers in the list.", oddNumbers);

Up Next
    Ebook Download
    View all
    Learn
    View all