[C#] 对List进行分组排序后输出

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 16:02   1215   0

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);
                }
            }

输出结果:

转载于:https://www.cnblogs.com/linhuide/p/8542223.html

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP