顾名思义,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表达式。
最后得到的结果如下图所示。