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
- var lQuery = from < object > in < table_Name or List_Name > where < object > . < column_name > < relational operator > < Condition_to_satisfied > select < object > . < column_name > ;
eg
- Var lQuery=from o in Orders
- where o.CustomerID == 84
- select o.Cost;
Computed column
Note that you can perform whatever computation you wish inside the anonymous type initializer.
eg
- var lQuery= from o in Orders
- where o.CustomerID == 84 select new { o.OrderID, o.Cost, CostWithTax = o.Cost * 10 };
Computed column with check constraint
eg
- var lQuery= from o in Orders
- where o.CustomerID == 84 && o.Cost > 100
- select new { o.OrderID, o.Cost, CostWithTax = o.Cost * 10 };
Ordering (sorting)
This is achieved by using the new “orderby” keyword.
eg
- var lQuery= from o in Orders
- where o.CustomerID == 84
- orderby o.Cost ascending
- select new { o.OrderID, o.Cost };
- var Found = from o in Orders
- where o.CustomerID == 84
- 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
- var lQuery = from o in Orders
- from c in Customers
- where o.CustomerID == c.CustomerID
- select new { c.Name, o.OrderID, o.Cost };
Grouping
A list of matching objects,
eg
-
- var lQuery = from o in Orders
- group o.Cost by o.CustomerID;
-
- foreach(var Cust in lQuery)
- {
-
- Console.WriteLine(“Customer with ID” + Cust.Key.ToString() + ”ordered” + Cust.Count().ToString() + ”items.”);
-
- foreach(var Cost in Cust)
- Console.WriteLine(”Cost: ” + Cost.ToString());
- }