August 29, 2010

Loop through Master-Detail Records using LINQ




Here’s an example of how to loop through Master-Detail Records using LINQ. I have taken the example of one Department containing multiple Employees. The example is taken only for the purpose of understanding and does not cover all scenarios.

class Program
{
static void Main(string[] args)
{


var lst = from d in dept
from e in dept.emp
select new { d, e };
foreach (var rec in lst)
{
Console.WriteLine("{0}, {1}", rec.d.DeptNm, rec.e.EmpNm);
}
Console.ReadLine();
}
}

class Department
{
public int DeptID { get; set; }
public string DeptNm { get; set; }
public IList<Employees> emp = new List<Employees>();
}

class Employees
{
public int EmpID { get; set; }
public string EmpNm { get; set; }
public string Address { get; set; }
}

As you can see, ‘dept’ is an object of class Department. The Department class contains a collection of Employees.

public IList<Employees> emp = new List<Employees>();


To loop through each Employees in a Department, we make use of the following LINQ Expression

var lst = from d in dept
from e in dept.emp
select new { d, e };
foreach (var rec in lst)
{
Console.WriteLine("{0}, {1}", rec.d.DeptNm, rec.e.EmpNm);
}


The list prints the Department Name and the Employees in it.

Giving me +1 tells me you liked this article! Thanks in advance




About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

0 Responses to "Loop through Master-Detail Records using LINQ"
 

Copyright © 2009-2013 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions