Tuesday, October 5, 2010

Grouping in Linq

A simple grouping in linq

var lst = (from employee in lstEmployee
select employee)
.OrderBy(emp => emp.ID)
.GroupBy(emp => emp.Name)

Use the following to union the collection

List<Employee> lstEmployeeCollection = new List<Employee>();
int Seq=1;

foreach (var employeeGrop in lst)

//Logic should go here for the existing collection modification 
//Use Union for making as a single collection
lstEmployeeCollection = (from employee in employeeGrop
select new Employee { ID = Seq, Name = employee.Name }

Another way of grouping is as follows .In this way we are not using the anonymous variable rather we are using typed variable

This Class will be as follows

public class Student 

public string Name { get; set; }
public int DeptID{ get; set; }
public int Marks { get; set; }


public class StudentDetails
public string Name { get; set; }
public List<Marks> lstCount { get; set; }


public class MarkDetails
public int DeptID { get; set; }
public int Marks { get; set; }


Now if we want the Studentdetails Group by student name ,and the result should contain the a list of studentsdetails that contains the dept as well as marks also...

The following lambda will gives this ...

List<StudentDetails> lstStudentDetails = lst
.GroupBy(x => x.Name)
(   x => new StudentDetails
{ Name = x.Key, lstCount = x.ToList()
.Select(y=>new MarkDetails{Marks =y.Marks ,DeptID =y.DeptID })

This way we can use the group by in a very simple way....

Enjoy coding........................


Post a Comment