Grouping output elements for generic lists in C #

Source: Internet
Author: User

Background: In the output list, you often need to group by a field, such as in the Output city list, according to the first letter grouping, output student list, according to the grade group, and then the results of the group sorted by other fields.

If the following Stu student classes exist, the code is as follows:

1      Public classSTU2     {3          Public intID {Get;Set; }4          Public stringName {Get;Set; }5          Public intAge {Get;Set; }6          Public stringCity {Get;Set; }7}

The following list of students exists:

1List<stu> stulist =NewList<stu>()2             {3                 NewStu{id=1, name="Lily", age= -, city="NewYork"},4                 NewStu{id=2, name="Lucy", age= -, city="NewYork"},5                 NewStu{id=1, name="Lilei", age= -, city="Beijing"}6};

First, according to the city group, in the same city students, according to the age of sorting, output, the code is as follows:

1             foreach(igrouping<string,stu> GroupinchStulist.groupby (c=>c.city))2             {3Console.WriteLine ("the current city is"+Group. Key);4                 foreach(STU STUinchGroup. (a=>a.age))5                 {6Console.Write (Stu. name+";");7                 }8 Console.WriteLine ();9}

Note that igroupoing has two parameters, the first parameter corresponds to the type of the grouping field, that is, if the type of the first parameter is a string, if it is grouped by city, the parameter type should be int if it is grouped by age. The second argument, which corresponds to the type of the list element, is Stu in this case.

Grouping output elements for generic lists in C #

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.