How is the usage of groupby in LINQ?

In LINQ, the GroupBy method is used to group elements in a sequence based on a specified key. It returns a sequence containing the grouped elements. The GroupBy method can take a key selector function to extract keys from the elements in the sequence. Here is the syntax for the GroupBy method:

public static IEnumerable<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>(
    this IEnumerable<TSource> source,
    Func<TSource, TKey> keySelector
)

In the above syntax, the source represents the sequence to be grouped, and the keySelector is a function that returns a key for each element.

Here is an example demonstrating how to use the GroupBy method:

var students = new List<Student>()
{
    new Student { Name = "John", Age = 20 },
    new Student { Name = "Jane", Age = 19 },
    new Student { Name = "Tom", Age = 20 },
    new Student { Name = "Alice", Age = 19 },
    new Student { Name = "Bob", Age = 21 }
};

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

foreach (var group in groupedStudents)
{
    Console.WriteLine($"Age: {group.Key}");

    foreach (var student in group)
    {
        Console.WriteLine($"Name: {student.Name}");
    }
}

In the above example, we used the GroupBy method to group students based on their age. Then, within a foreach loop, we iterate through each group and print out the age along with the student’s name.

The output will be as follows:

Age: 20
Name: John
Name: Tom

Age: 19
Name: Jane
Name: Alice

Age: 21
Name: Bob

The Student class in the above example is defined as follows:

public class Student
{
    public string Name { get; set; }
    public int Age { get; set; }
}

Please note that the GroupBy method returns an IEnumerable>, where IGrouping is an interface that represents a collection of elements with the same key.

广告
Closing in 10 seconds
bannerAds