SoFunction
Updated on 2025-03-07

C# method to implement generic List grouping output elements

This article describes the method of C# implementing generic List grouping output elements. Share it for your reference, as follows:

background: When outputting a list, you often need to group according to a certain field. For example, when outputting a city list, you need to group according to the first letter. When outputting a student list, you need to group according to the grade, and then sort the grouping results according to other fields.

If the following STU student class exists, the code is as follows:

public class STU
{
    public int ID { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    public string City { get; set; }
}

The following student list exists:

List<STU> stuList = new List<STU>()
{
    new STU{ID=1,Name="Lily",Age=18,City="NewYork"},
    new STU{ID=2,Name="Lucy",Age=20,City="NewYork"},
    new STU{ID=1,Name="LiLei",Age=18,City="BeiJIng"}
};

First group them according to the city, sort students in the same city according to their age, and output them separately. The code is as follows:

foreach (IGrouping&lt;string,STU&gt; group in (c=&gt;))
{
    ("The current city is" + );
    foreach (STU stu in (a=&gt;))
    {
      (+";");
    }
    ();
}

Notice, IGroupoing has two parameters. The first parameter corresponds to the type of the grouping field. That is to say, if it is grouped by city, the type of the first parameter should be string. If it is grouped by age, the parameter type should be int. The second parameter corresponds to the type of the List element, which is STU in this example.

For more information about C# related content, please check out the topic of this site:Tutorial on the usage of common C# controls》、《Summary of WinForm control usage》、《C# data structure and algorithm tutorial》、《Introduction to C# object-oriented programming tutorial"and"Summary of thread usage techniques for C# programming

I hope this article will be helpful to everyone's C# programming.