Thursday, 31 May 2012

What is Language Integriated Query(LINQ) in .net?

LINQ: Language Integrated Query


Language integrated Query(linq) is a new  way of programming model.
till now we know c# coding like class,objects,interfaces,….ect now linq also same object oriented Programming language but way of writing is different then normal c# coding. In LINQ every is a query like OUR DATABASE QUERIES, and we can find more fimilarities to quering the objects or databases or xml files, dataset,…ect which are all now concepts in linq programming model.

Those are
Linq to objects,
Linq to sqlserver(till .net 3.5), ------Object Relational Model (tool)*
Linq to xml,
linq to dataset,Linq to Entities…ect
Linq  has so many Extension Methods, Operators to build  a query in .Net 3.5 onwords.
What is Extension methods?
Extension method is an additional method to existing classes. So in .net 3.5 instead of preparing new libraries/assemblies, they prepares static classes like
public static class Enumerable
{
-----all static methods // which are called as Extension methods.
Adding new Extension methods to System.collections and System.Collections.Generic
Example:
public static decimal Average<TSource>(this IEnumerable<TSource> source, Func<TSource, decimal> selector);
Here Average<TSource> method is added to Existing Interface(IEnumerable<T>) of System.Collections.Generic
Note: Every Extension method return type is IEnumerable<TSource>(optionally Var keyword) because Linq is Strong type language.
}
---ect many static classes in .net 3.5 in their further linq libraries.and we can consider these are good in Programming and Good Standarization development.

Some basic operators in Linq
Till now c#
  int[] intarr = new int[5] { 10, 20, 30, 40, 50 };

 now query the object by using Index way
 like
intarr[0],intarr[1],intarr[2]…..ect  
and uses foreach or IEnumerable of Enumeration.    

Index based Quering an object.
Here Object is intarr
Now in Linq we can query the object
int[] intarr = new int[5] { 10, 20, 30, 40, 50 };
    var dataobject = from n in intarr select n;                                                                 

dataobject is one more object for intarr in linq style but here not required because intarr is already an object why again object(dataobject). So whenever we require a contidion based like(indexing in c#) we have use then simplify the work with new style of programming style.

  int[] intarr = new int[5] { 10, 20, 30, 40, 50 };
var dataobject = from n in
                                                                intarr // intarr[5]={10,20,30,40,50}
select n; 

var dataobject = from n in dataobject select n;
Here:
·         The 'from' keyword logically loops through the contents of the collection.
·         The expression with the 'where' keyword is evaluated for each object in the collection.
·         The 'select' statement selects the evaluated object to add to the list being returned.
·         The 'var' keyword is for variable declaration. Since the exact type of the returned object is not known, it indicates that the information will be inferred dynamically.
LINQ query can be applied to any data-bearing class that inherits from IEnumerable<T>, here T is any data type, for example List<Book>.
Note: the return type should be IEnumerable<T> type why because this it base interface for Linq.

1st way
      foreach (var item in dataobject)// not intarr object
      {
          Label1.Text += "  "+ item.ToString();
      }
Or here also we can use int also like

2nd way

foreach (int item in dataobject)
        {
            Label1.Text += "  " + item.ToString();
        }

  3rd way:

Proper way of implementation

IEnumerator<int> ier = dataobject.GetEnumerator();
        while (ier.MoveNext())
        {
            int i = (int)ier.Current;
            Label1.Text += i.ToString();
       
        }
Here we can use Var datatype instead of IEnumerable<int> but we clearly know what object we can getting from our query so if we know writing is good.
Instead of Var.

How to use Where clause

IEnumerable<int> dataobject = from n in
intarr where n = =20 select n;

This above query is converted(complied) like below automatically when executed by complier.

IEnumerable<int> dataobject = from n in
intarr.Where(n => n == 20)
select n;
Here intarr is source like intarr[5]={10,20,30,40,50} then here only condition is checked then execution is started.

Like we query basic objects as well we can query custom object like Employee,Student,customer…..ect

Example:
         1st Perpare a type
                   2nd Prepare an object
                   3rd Query the object
Prepare an object

1st prepare a type –Employee
  public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Salary { get; set; }
        public Employee()
        {
       
       
        }
        public Employee(int id, string name, int salary)
        {
            this.Id = id;
            this.Name = name;
            this.Salary = salary;
        }
    
        public override string ToString()
        {
            return string.Format(" {0}, {1} (£{2}) <br />", Id, Name, Salary);
        }
    }
2nd create object

List<Employee> employees = new List<Employee>
       {
            new Employee(101, "Anand", 40000),
            new Employee(102, "Balasubramanium", 32000),
            new Employee(103, "Charan", 29000),
            new Employee(104, "Dinesh", 20000)    };
        var developers = Employee.Where(n => n.Name.Contains("Charan"));
        foreach (Employee item in Employee)
        {
            Label1.Text += "  " + item.ToString();  // this is static intellisense
        }

3rd query an object
Linq Style

      var developers = employees.Where(n => n.Name.Contains("Charan"));

Display

foreach (Employee item in employees)
        {
            Label1.Text += "\n  " + item.ToString();  // this is static intellisense
        }

How to write a join query in Linq?

Now I Created one more class is called Department then where have common key like forgin key value.

        List<Department> depts = new List<Department>();
        depts.Add(new Department { Id = 101, DeptName = "Dotnet", DeptLoc = "USA" });
        depts.Add(new Department { Id = 102, DeptName = "java", DeptLoc = "UK" });
        var deptsobj = from d in depts select d;

        var joindata = from n in empsobj join s in deptsobj on n.Id equals s.Id select new { n.Name, s.DeptName };


        foreach (var title in joindata)
            Label1.Text += String.Format("{0} {1} <br />", title.Name,title.DeptName);

No comments:

Post a Comment