LINQ HAND BOOK FOR BEGINNERS

What is Linq

Linq is short for Language Integrated Query. If you are used to using SQL to query databases, you are going to have something of a head start with Linq, since they have many ideas in common. Before we dig into Linq itself, let’s step back and look at what makes SQL different from C#.

Syntax

  1. var lQuery = from < object > in < table_Name or List_Name > where < object > . < column_name > < relational operator > < Condition_to_satisfied > select < object > . < column_name > ;  
eg
  1. Var lQuery=from o in Orders  
  2. where o.CustomerID == 84  
  3. select o.Cost;  
Computed column

Note that you can perform whatever computation you wish inside the anonymous type initializer.

eg
  1. var lQuery= from o in Orders  
  2. where o.CustomerID == 84 select new { o.OrderID, o.Cost, CostWithTax = o.Cost * 10 };  
Computed column with check constraint

eg
  1. var lQuery= from o in Orders  
  2. where o.CustomerID == 84 && o.Cost > 100  
  3. select new { o.OrderID, o.Cost, CostWithTax = o.Cost * 10 };  
Ordering (sorting)

This is achieved by using the new “orderby” keyword.

eg
  1. var lQuery= from o in Orders  
  2. where o.CustomerID == 84  
  3. orderby o.Cost ascending  
  4. select new { o.OrderID, o.Cost };  
  5. var Found = from o in Orders  
  6. where o.CustomerID == 84   
  7. orderby o.Cost descending select new { o.OrderID, o.Cost };  
Getting Values From multiple Tables

It is achieved by using the “from” keyword multiple times.

eg
  1. var lQuery = from o in Orders   
  2. from c in Customers   
  3. where o.CustomerID == c.CustomerID  
  4. select new { c.Name, o.OrderID, o.Cost };  
Grouping

A list of matching objects,

eg
  1. // Group orders by customer.  
  2. var lQuery = from o in Orders  
  3. group o.Cost by o.CustomerID;  
  4. // Iterate over the groups.   
  5. foreach(var Cust in lQuery)   
  6. {  
  7.     // About the customer…  
  8.     Console.WriteLine(“Customer with ID” + Cust.Key.ToString() + ”ordered” + Cust.Count().ToString() + ”items.”);  
  9.     // And the costs of what they ordered.  
  10.     foreach(var Cost in Cust)  
  11.     Console.WriteLine(”Cost: ” + Cost.ToString());  
  12. }