1. 程式人生 > >[C#] 對List進行分組排序後輸出

[C#] 對List進行分組排序後輸出

pos 學生 new C# src key 輸出 分組 groupby

Student 類:

    public class Student
    {
        public int ID { get; set; }

        public string Name { get; set; }

        public int Age { get; set; }

        public string Sex { get; set; }
    }

Demo:

            List<Student> lsStudent = new List<Student>() 
            {
                new Student { ID = 1 ,Name = "1", Age = 25, Sex = "男" },
                new Student { ID = 2, Name = "2", Age = 18, Sex = "女" },
                new Student { ID = 3, Name = "3", Age = 13, Sex = "男" },
                new Student { ID = 4, Name = "4", Age = 23, Sex = "男" },
                new Student { ID = 5, Name = "5", Age = 22, Sex = "女" }
            };

            foreach (IGrouping<string, Student> group in lsStudent.GroupBy(x => x.Sex))
            {
                Console.WriteLine("當前學生的性別是:{0}", group.Key);
                foreach (Student student in group.OrderBy(a => a.Age))//不排序直接輸出的話:Student student in group
                {
                    Console.WriteLine("姓名:" + student.Name + " 年齡:" + student.Age);
                }
            }

輸出結果:

技術分享圖片

[C#] 對List進行分組排序後輸出