Group By using LINQ

Posted by Rajesh_Kumar under LINQ category on | Points: 40 | Views : 597
We will take the person class as in my earlier example(Use of Let keyword) as:

List<Person> obj_persons = new List<Person>
new Person { FirstName="Rajesh", LastName="Sathua" },
new Person { FirstName="Vinod", LastName="Shinde" },
new Person { FirstName="Rajesh",LastName="Sharma" },
new Person { FirstName="Rutu", LastName="Dixit" },
new Person { FirstName="Vinod", LastName="Bhaskar" },
new Person { FirstName="Rutu", LastName="Bhonde" },
new Person { FirstName="Preeti", LastName="Naik" },
new Person { FirstName="Rutu", LastName="Ahuja" },
new Person { FirstName="Rutu", LastName="Panday" },
new Person { FirstName="Preeti", LastName="Panday" },

var groups = from p in obj_persons
group p by p.FirstName into g //into keyword is used for strong items into separate collections
select new {GroupName = g.Key, LastName = g};

//loop through the groups
foreach(var g in groups)
Response.Write(string.Format("Duplicate Name of {0} in Organisation: ",g.GroupName) + "<br/>");

foreach(var name in g.LastName)
Response.Write(string.Format("---{0}", name.FirstName + " " + name.LastName) + "<br/>");


Duplicate Name of Rajesh in Organisation:
---Rajesh Sathua
---Rajesh Sharma

Duplicate Name of Vinod in Organisation:
---Vinod Shinde
---Vinod Bhaskar

Duplicate Name of Rutu in Organisation:
---Rutu Dixit
---Rutu Bhonde
---Rutu Ahuja
---Rutu Panday

Duplicate Name of Preeti in Organisation:
---Preeti Naik
---Preeti Panday

Comments or Responses

Login to post response