lambda表达式嵌套

顾名思义,lambda表达式嵌套就是在lambda表达式中嵌套使用lambda表达式。本文通过一个小实例来说明lambda表达式嵌套。
在开发时需要完成”对集合中的数据分组,再按照每个分组中某个特定数据对分组进行排序”的操作。本文使用学生集合作为数据源。
下面是完整的示例代码。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LinqInLinqExps
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Student> studentList = new List<Student>()
            {
                new Student(){Age=15,Name="zs",ClassId=1},
                new Student(){Age=12,Name="zss",ClassId=2},
                new Student(){Age=18,Name="xfs",ClassId=1},
                new Student(){Age=15,Name="fd",ClassId=3},
                new Student(){Age=15,Name="rf",ClassId=1},
                new Student(){Age=17,Name="df",ClassId=2},
                new Student(){Age=11,Name="sd",ClassId=3},
                new Student(){Age=14,Name="er",ClassId=2},
                new Student(){Age=20,Name="ss",ClassId=2}
            };
            var groupedStudentList = studentList.GroupBy(it => it.ClassId).OrderByDescending(g => g.Max(it=>it.Age));
            foreach (var g in groupedStudentList)
            {
                foreach (var item in g)
                {
                    Console.WriteLine(item.ClassId + ";" + item.Age + ";" + item.Name);
                }
            }
            Console.ReadLine();
        }
    }

    class Student
    {
        public int Age { get; set; }
        public string Name { get; set; }
        public int ClassId { get; set; }
    }
}

代码中与文章主题有关的代码仅下面一行:

var groupedStudentList = studentList.GroupBy(it => it.ClassId).OrderByDescending(g => g.Min (it=>it.Age));

这行代码先按照班级ID对学生进行分组,接着按照每个分组中学生年龄的最小值对班级进行降序排序。其中“计算每个分组学生年龄的最小值”的操作便是嵌套使用lambda表达式。
最后得到的结果如下图所示。
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值