Wednesday, October 10, 2012

LINQ



What is LINQ?
Basically LINQ address the current database development model in the context of Object Oriented Programming Model. If someone wants to develop database application on .Net platform the very simple approach he uses ADO.Net. ADO.Net is serving as middle ware in application and provides complete object oriented wrapper around the database SQL. Developing application in C# and VB.Net so developer must have good knowledge of object oriented concept as well as SQL, so it means developer must be familiar with both technologies to develop an application. If here I can say SQL statements are become part of the C# and VB.Net code so it’s not mistaken in form of LINQ. According to Anders Hejlsberg the chief architect of C#.

             “Microsoft original motivation behind LINQ was to address the impedance mismatch between programming languages and database.”

LINQ has a great power of querying on any source of data, data source could be the 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.

  • LINQ to Object {Queries performed against the in-memory data}
  • LINQ to ADO.Net
    • LINQ to SQL (formerly 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 {Microsoft ORM solution}
  • LINQ to XML (formerly XLinq) { Queries performed against the XML source}

I hope few above lines increase your concrete knowledge about Microsoft LINQ and now we write some code snippet of LINQ.

1. Code Snippet
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);
Output:
0
1
2


All SQL Operates are available in LINQ to Object like Sum Operator in the following code.

2. Code Snippet
int[] nums = new int[] {2,4,6,2};
int result = nums.Sum();
Console.WriteLine(result);

Output:
1
2

One thing that I want to share with you guys is LINQ to Object support querying against any object that inherits from IEnumerable (all .Net collection inherits from IEnumerable interface). LINQ to Object provided main types of Operator Type that are give below.


Operator Types
Operator Name
Aggregation
  • Aggregate
  • Average
  • Count
  • LongCount,
  • Max,
  • Min,
  • Sum
Conversion
  • Cast,
  • OfType,
  • ToArray,
  • ToDictionary,
  • ToList,
  • ToLookup,
  • ToSequence
Element
  • DefaultIfEmpty,
  • ElementAt,
  • ElementAtOrDefault,
  • First,
  • FirstOrDefault,
  • Last,
  • LastOrDefault,
  • Single,
  • SingleOrDefault
Equality
  • EqualAll
Generation
  • Empty,
  • Range,
  • Repeat
Grouping
  • GroupBy
Joining
  • GroupJoin,
  • Join
Ordering
  • OrderBy,
  • ThenBy,
  • OrderByDescending,
  • ThenByDescending,
  • Reverse
Partitioning
  • Skip,
  • SkipWhile,
  •  Take,
  •  TakeWhile
Quantifiers
  • All,
  • Any,
  • Contains
Restriction
  • Where
Selection
  • Select,
  • SelectMany
Set
  • Concat,
  • Distinct,
  • Except,
  • Intersect,
  • Union

To the good use of above operator types I need samle patient class so here it
using System;

public class 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; }
    }
}

Here is my code that intiliaze patients object with following data.

List<Patient> patients = new List<Patient> {
           new Patient { PatientName="Ali Khan", Age=20, Gender="Male" , Area = "Gulshan"},
           new Patient { PatientName="Ahmed Siddiqui", Age=25 ,Gender="Male", Area = "NorthKarachi" },
           new Patient { PatientName="Nida Ali", Age=20, Gender="Female", Area = "NorthNazimabad"},
           new Patient { PatientName="Sana Khan", Age=18, Gender="Female", Area = "NorthNazimabad"},
           new Patient { PatientName="Shahbaz Khan", Age=19, Gender="Male", Area = "Gulshan"},
           new Patient { PatientName="Noman Altaf", Age=19, Gender="Male", Area = "Gulshan"},
           new Patient { PatientName="Uzma Shah", Age=23, Gender="Female", Area = "NorthKarachi"}};

Patient p = new Patient();
        p.Age =33; p.Gender = "male";
        p.PatientName = "Hammad Ali"
        p.Area = "Defence";         
        patients.Add(p);


This code snippet fetch those records whose gender is equal to “Male”. 
   gdView.DataSource = from pa in patients
                        where pa.Gender == "Male"
                        orderby pa.PatientName, pa.Gender, pa.Age
                        select pa;
   gdView.DataBind();

The following code snippet 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);
        }
 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);
     }
 }
This code snippet determine the count of those records, which lay in above 20 years. 
int patientCount = (from pa in patients
                    where pa.Age > 20
                    orderby pa.PatientName, pa.Gender, pa.Age
                    select pa).Count();

All the above codes are few example of LINQ to Object technique of LINQ.

No comments:

Post a Comment

Mixed Content: The page at xxx was loaded over HTTPS, but requested an insecure

 Mixed Content: The page at ' https ://www.test.com/signup.aspx' was loaded over HTTPS, but requested an insecure script ' http ...