List分组一

时间:2021-07-02 05:42:21
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Data.SqlClient;

using System.Data;
class Program
{
    static void Main(string[] args)
    {
        List<Student> list = new List<Student>()
           {
           ,StuNo="a001"},
           ,StuNo="a003"},
           ,StuNo="b001"},
           ,StuNo="b045"},
           ,StuNo="c001"},
           ,StuNo="c008"},
           ,StuNo="c050"},
           ,StuNo="c007"}
           };
        Dictionary<string, List<Student>> stuGroup = new Dictionary<string, List<Student>>();

        foreach (Student item in list)
        {
            if (!stuGroup.Keys.Contains(item.ClassName))
            {
                stuGroup.Add(item.ClassName, new List<Student>());
            }
            stuGroup[item.ClassName].Add(item);

        }
        foreach (KeyValuePair<string, List<Student>> item in stuGroup)
        {
            Console.WriteLine("班级:" + item.Key);
            foreach (Student stu in item.Value)
            {
                Console.WriteLine("姓名:" + stu.Name + "\t班级:" + stu.ClassName + "\t年龄:" + stu.Age + "\t学号:" + stu.StuNo);
            }
        }
        Console.Read();
    }
}
class Student
{
    public string Name { get; set; }

    public string ClassName { get; set; }

    public int Age { get; set; }

    public string StuNo { get; set; }

}