如何在EF中选择另一个列表的列表

时间:2015-03-03 09:35:55

标签: c# linq entity-framework

我有这个班级

public class Student
{
    public string Name { get; set; }
    public int Grade { get; set; }
}

我用这种方法填写我的清单,

private static void FillLists()
{
    List<Student> lststudent = new List<Student>();
    lststudent.Add(new Student { Name = "Arash", Grade = 12 });
    lststudent.Add(new Student { Name = "Kamran", Grade = 13 });
    lststudent.Add(new Student { Name = "koroush", Grade = 16 });

    List<Student> lststudent2 = new List<Student>();
    lststudent2.Add(new Student { Name = "Arman", Grade = 18 });
    lststudent2.Add(new Student { Name = "Aria", Grade = 10 });
    lststudent2.Add(new Student { Name = "Daryoush", Grade = 20 });

    List<List<Student>> students = new List<List<Student>>();
    students.Add(lststudent);
    students.Add(lststudent2);
}

我的问题是如何获得grade > 15学生的名单?

4 个答案:

答案 0 :(得分:1)

要获得简单易用的解决方案,请尝试以下方法:

var st = students.SelectMany (s => s).Where(s=>s.Grade>15).ToList();

答案 1 :(得分:0)

尝试这样的事情

    students.Add(lststudent.Where(s=>s.Grade>15).ToList());
    students.Add(lststudent2.Where(s=>s.Grade>15).ToList());

使用一行代码

students.Add(lststudent.Where(s=>s.Grade>15).Concat(lststudent2.Where(s=>s.Grade>15)).ToList());

在评论中,您可以将代码更改为只有一个lstStudent并根据需要对其进行过滤

 var studentWith15grade =     lststudent.Where(s=>s.Grade>15).ToList();  

答案 2 :(得分:0)

foreach()

List<List<Student>> students的解决方案
List<Student> Filtered = new List<Student>(); // Filtered list with students with grade > 15

// Foreach List<Student> in students list
foreach (List<Student> mylist in students)
{
     // Foreach student class in selected list
     foreach (Student student in mylist)
     {
          // check grade > 15 and add if so to filtering list
          if (student.Grade>15)
          {
               Filtered.Add(student);
           }
      }
}

答案 3 :(得分:0)

您可以将列表合并为一个:

var finalList = new List<Student>(lststudent);
finalList.AddRange(lstStudent2);
// then you can query on finalList 
var result = finalList.Where(s => s.Grade > 15);