如何使用具有多对多关系的LINQ Lambda表达式获取正确的数据

时间:2017-04-19 17:09:45

标签: c# linq

看起来像一个非常简单的情况,但我无法在脑中或在stackoverflow中找到适当的lambda表达式:(感谢所有帮助。

案例看起来很简单。我有两个类和关系,它们之间有很多对。

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

        public List<Document> Documents { get; set; }
    }

    public class Document
    {
        public int Id { get; set; }
        public string Name { get; set; }

        public List<Student> Students { get; set; }
    }

然后我启动了一些值:

        Student st1 = new Student { Id = 1, Name = "Student 1" };
        Student st2 = new Student { Id = 2, Name = "Student 2" };
        Student st3 = new Student { Id = 3, Name = "Student 3" };

        List<Student> listStudent12 = new List<Student>(); 
        listStudent12.Add(st1); 
        listStudent12.Add(st2);

        List<Student> listStudent23 = new List<Student>();
        listStudent23.Add(st2); 
        listStudent23.Add(st3);


        Document doc1 = new Document { Id = 1, Name = "doc 1", Students = listStudent12 };
        Document doc2 = new Document { Id = 2, Name = "doc 2", Students = listStudent23 };

        List<Document> listDocs = new List<Document>();
        listDocs.Add(doc1);
        listDocs.Add(doc2);

现在我想获得一个使用linq lambda表达式的文档列表,它们与“Student 3”(id:3)相关。

我试过这样:

var result = listDocs.Where(d => d.Students.FirstOrDefault().Id == 3).ToList();

但它返回null(我想我知道为什么 - 第一个返回的学生不等于3)。

我希望结果包含所有ID = 3的学生名单中的文件。 我坚持到这里需要帮助。提前谢谢你。

在SQL级别,我会去:

SELECT Document.* from Document, DocumentStudent WHERE Document.Id = DocumentStudent.DocumentId AND DocumentStudent.StudentId = 3

2 个答案:

答案 0 :(得分:1)

您在示例中所做的是找到首先Document Student Id: 3的{​​{1}}。最终没有。

您想要做的是:

var result = listDocs.Where(doc => doc.Students.Any(st => st.Id == 3).ToList();

它会评估至少有一个Document Student的任何Id: 3

答案 1 :(得分:0)

如果您使用以下语法

,我认为它看起来会更简单
var result = (from doc in listDocs
              from student in doc.Students
              where student.Id == 3
              select doc).ToList();