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.
Tweet
No comments:
Post a Comment