Sample LINQ Queries in .net

Posted on May 20 2010 by Sachin Jain

1) Simple Query

var CustQuery= from cust in customers
select cust;
2) Where Clause

var DelhiCustomerQuery = from cust in customers
where cust.City == “Delhi”
select cust;
Logical Operator
where cust.City==”delhi” && cust.Name == “mumbai”
3) Order by
var DelhiCustomerQuery = from cust in customers where cust.City == “Delhi” orderby cust.Name ascending
select cust;
4) Group by
var QueryGroupByCity = from cust in customers group cust by cust.City
Now here is trick while reading it
foreach (var customerGroup in QueryGroupByCity )
{
Console.WriteLine(customerGroup.Key);
foreach (Customer customer in customerGroup)
{
Console.WriteLine(”    {0}”, customer.Name);
}
}
Using Having
var custQuery =  from cust in customers group cust by cust.City into custGroup where custGroup.Count() > 2 orderby custGroup.Key
select custGroup;
5) Inner Join
var innerJoinQuery = from category in categories join prod in products on category.ID equals prod.CategoryID
select new { ProductName = prod.Name, Category = category.Name };  // This is for selecting desired columns
6) Left Join
var leftOuterJoinQuery = from category in categories join prod in products on category.ID equals prod.CategoryID into prodGroup from item in prodGroup.DefaultIfEmpty(new Product{Name = String.Empty, CategoryID = 0})
select new { CatName = category.Name, ProdName = item.Name }; // This is for selecting desired columns
VN:F [1.9.0_1079]
Rating: 0.0/5 (0 votes cast)
VN:F [1.9.0_1079]
Rating: 0 (from 0 votes)

Leave a Reply

Get Adobe Flash playerPlugin by wpburn.com wordpress themes

Powered by Sachin Jain

Powered by Olark