使用 LINQ 筛选列表

Filter lists with LINQ

我有,列出 StudentsTeachers

var students = new List<Student>
    {
        new Student
        {
            Id= 1,
            Name = "AA",
            City = "London",
            Country = "UK"
        },
        new Student
        {
            Id= 2,
            Name = "BB",
            City = "New Orleans",
            Country = "USA"
        }
    }

var teachers = new List<Teacher>
    {
        new Teacher
        {
            Id = 1,
            Name = "CC",
            City = "Berlin",
            Country = "Germany"
        },
        new Teacher
        {
            Id = 2,
            Name = "DD",
            City = "Mexico D.F.",
            Country = "Mexico"
        }
    }

我想为每位老师获取位于同一国家和同一城市的学生列表。

到目前为止我做了什么:

var result = from teacher in teachers
                     select new
                     {
                         teacher,
                         Students = students.Where(s => s.Country == teacher.Country && s.City == teacher.City).ToList()
                     };

这没用,我得到了 casting exception。并尝试:

var result = new List<(Teacher, IEnumerable<Student>)>();

teachers.ToList().ForEach(c => result.Add((c,
        students.Where(s => s.Country == c.Country && s.City == c.City).ToList())));

这很好用,但是有没有其他方法,不用循环?

您的 linq 查询是正确的。您的查询 return 是一个匿名类型的列表。您不能将其直接转换为元组列表。 您遇到的问题是您要转换为哪种类型。如果你想得到像 IEnumerable<(Teacher, IEnumerable)> 这样的元组列表的结果,你应该编码如下:

        var result = from teacher in teachers
                     select (
                         teacher,
                         students.Where(s => s.Country == teacher.Country && s.City == teacher.City).ToList()
                         );

那么, result.ToList() 会给你一个元组列表, result.ToArray() 会给你一个 Tuple

数组

Lambda 表达式备选方案:

var result = teachers
            .Select(teacher => (teacher, students.Where(s => s.Country == teacher.Country && s.City == teacher.City).ToList()));

但是,我更喜欢匿名列表作为 return 类型而不是元组。