LINQ and various types of joins
Posted on 4/22/2010 7:56:28 PM
in #Asp.Net 3.X
While working with data most of the time we have to work with relation between different lists of data. Many a times we want to fetch data from both the list at once. This requires us to make different kind of joins between the lists of data. /P>
LINQ support different kinds of join /P>
Inner Join/P>
/SPAN>List<Customer> customers = GetCustomerList();/P>
/SPAN>List<Supplier> suppliers = GetSupplierList();/P>
/o:p>/P>
/SPAN>var custSupJoin = /P>
/SPAN>from sup in suppliers/P>
/SPAN>join cust in customers on sup.Country equals cust.Country/P>
/SPAN>select new { Country = sup.Country, SupplierName = sup.SupplierName, CustomerName = cust.CompanyName };/P>
Group Join – where By the joined dataset is also grouped./P>
/SPAN>List<Customer> customers = GetCustomerList();/P>
/SPAN>List<Supplier> suppliers = GetSupplierList();/P>
/o:p>/P>
/SPAN>var custSupQuery =/P>
/SPAN>from sup in suppliers/P>
/SPAN>join cust in customers on sup.Country equals cust.Country into cs/P>
/SPAN>select new { Key = sup.Country, Items = cs };/P>
We can also work with the Left outer join in LINQ like this./P>
/SPAN>List<Customer> customers = GetCustomerList();/P>
/SPAN> /SPAN>List<Supplier> suppliers = GetSupplierList();/P>
/o:p>/P>
/SPAN>var supplierCusts = /P>
/SPAN>from sup in suppliers/P>
/SPAN>join cust in customers on sup.Country equals cust.Country into cs/P>
/SPAN>from c in cs.DefaultIfEmpty() /SPAN>//// DefaultIfEmpty preserves left-hand elements that have no matches on the right side /P>
/SPAN>orderby sup.SupplierName/P>
/SPAN>select new { Country = sup.Country, CompanyName = c == null ? "(No customers)" : c.CompanyName,/P>
/SPAN>SupplierName = sup.SupplierName};/P>Vikram/SPAN>
|
Posted on 8/23/2010 8:20:52 AM
good work , thanks Mr.Vikram for simplying LINQ.
/p>
|