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.

Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) 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 is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: