Monday, 2 January 2017

Grouping a Collection using Linq in various ways

In this post we  are going to see how to grouping a collection in Linq




public abstract class Person
{
    public int ID { setget; }

    public string Name { setget; }

    public int PhoneNumber { setget; }

    public string Address { setget; }
}


public class Student:Person
{
    public string Department { setget; }

    public int TotalMarks { setget; }

}




        List<Student> StudentList = new List<Student>() {

            new Student(){ ID =4,
Name="Suresh",
Address="Porur",
TotalMarks=350,
Department="ECE",
PhoneNumber=12321312
},
            new Student(){ ID=2,
Name="Ramu",
Address="Delhi",
TotalMarks=450,
Department="CSE",
PhoneNumber=23233112
},
             new Student(){
ID=1,
Name="Rajesh",
Address="Madurai",
TotalMarks=400,
Department="ECE",
PhoneNumber=3434322
},
            new Student(){
ID=3,
Name="Rajesh",
Address="Chennai",
TotalMarks=460,
Department="CSE",
PhoneNumber=43434223
},
            new Student(){
ID=5,
Name="Hanish",
Address="Salem",
TotalMarks=420,
Department="EEE",
PhoneNumber=34423232
}

        };





IEnumerable<IGrouping<string,Student>> grpstuds = StudentList.GroupBy(x => x.Department);

Console.WriteLine("Grouping Students Linq .... ");
        
foreach (var item in grpstuds)
{
        Console.WriteLine(string.Format("Department : {0}", item.Key));

        foreach (var stu in item)
        {
            Console.WriteLine(string.Format("ID : {0}, Name {1}", stu.ID, stu.Name));
        }
 }



Output:
*************

Grouping Students Linq ....

Department : ECE
ID : 4, Name Suresh
ID : 1, Name Rajesh

Department : CSE
ID : 2, Name Ramu
ID : 3, Name Rajesh

Department : EEE
ID : 5, Name Hanish.





        varsqlgrpstuds =    from stud in StudentList
                            group stud by stud.Department into grp
                            select grp;

        Console.WriteLine("Grouping Students Linq to Sql .... ");



        foreach (var item in sqlgrpstuds)
        {
            Console.WriteLine(string.Format("Department : {0}", item.Key));

            foreach (var stu in item)
            {
                Console.WriteLine(string.Format("ID : {0}, Name {1}", stu.ID, stu.Name));
            }
        }



        Console.Read();



Output:
*******************

Grouping Students Linq to Sql ....

Department : ECE
ID : 4, Name Suresh
ID : 1, Name Rajesh

Department : CSE
ID : 2, Name Ramu
ID : 3, Name Rajesh

Department : EEE
ID : 5, Name Hanish



From this post we can learn how to use the groupby method in Linq to group a collection in various ways

No comments:

Post a Comment