linq group in csharp

In C#, LINQ GroupBy method is used to group the items in a collection based on a key. The syntax for using GroupBy is:

main.cs
var groupedList = collection.GroupBy(item => item.Key);
56 chars
2 lines

Here, collection is the collection on which grouping is to be performed, item is each item in the collection, and item.Key is the property based on which grouping is to be performed. The result returned by this method is a collection of IGrouping<TKey, TElement> where TKey is the type of the key in the group and TElement is the type of the elements in the group.

Example:

main.cs
class Student
{
    public string Name { get; set; }
    public string Gender { get; set; }
    public int Age { get; set; }
}

List<Student> students = new List<Student>()
{
    new Student() {Name = "John", Gender = "Male", Age = 18},
    new Student() {Name = "Sarah", Gender = "Female", Age = 22},
    new Student() {Name = "Mason", Gender = "Male", Age = 20},
    new Student() {Name = "Emily", Gender = "Female", Age = 18},
    new Student() {Name = "Alex", Gender = "Male", Age = 22}
};

var groupedStudents = students.GroupBy(s => s.Gender);

foreach (var group in groupedStudents)
{
    Console.WriteLine("Group: " + group.Key);

    foreach (var student in group)
    {
        Console.WriteLine("Name: {0}, Gender: {1}, Age: {2}", student.Name, student.Gender, student.Age);
    }
}
794 chars
28 lines

In the above example, we have a collection of students which we want to group based on gender. We use the GroupBy method to get the groups of male and female students. Finally, we loop through each group and print the students in that group.

gistlibby LogSnag