LINQ双左连接

时间:2010-10-20 01:20:58

标签: linq join object

我有一个名字的学生班,一个带有学生姓名和条目名称的blogEntries班,以及一个带有作业名称的blogAssignments班。

我想向所有学生展示他们创建的blogEntries,其标题与blogAssignments.assignmentName匹配。

我有以下LINQ查询,但我无法确定在blogAssignments中加入的位置:

var results =
                from person in HACCStudents
                join bEntry in blogEntries on person.FullName equals bEntry.AuthorFullName
                into studentBlogEntries
                from studentBlogEntry in studentBlogEntries.DefaultIfEmpty()
                orderby person.FullName
                select new { PersonName = person.FullName, 
                    BlogTitle=studentBlogEntry != null ?studentBlogEntry.Title : ""


                };

1 个答案:

答案 0 :(得分:3)

修改

这是我编写的测试用例,我认为使用LINQ to Objects符合您的要求:

public class Person
{
    public string FullName;
}

public class BlogEntry
{
    public string AuthorFullName;
    public string Title;
}

public class BlogAssignment
{
    public string AssignmentName;
}

public void GetStudentsWithAssignments()
{
    var students = new List
    {
        new Person { FullName = "Bob Doe" },
        new Person { FullName = "Steve Carrell" },
        new Person { FullName = "John West" },
        new Person { FullName = "Alice Croft" },
        new Person { FullName = "Al Bean" }
    };

    var entries = new List
    {
        new BlogEntry { AuthorFullName = "Steve Carrell", Title = "100 ways to skin a cat" },
        new BlogEntry { AuthorFullName = "Steve Carrell", Title = "LINQ sux arze" },
        new BlogEntry { AuthorFullName = "John West", Title = "Salmon bake 2007" },
        new BlogEntry { AuthorFullName = "John West", Title = "Make my day" },
        new BlogEntry { AuthorFullName = "Al Bean", Title = "An inconvenient tooth" }
    };

    var assignments = new List
    {
        new BlogAssignment { AssignmentName = "Salmon bake 2007" },
        new BlogAssignment { AssignmentName = "LINQ sux arze" },
        new BlogAssignment { AssignmentName = "Make my day" }
    };

    var subquery =
        from e in entries
        join a in assignments on e.Title equals a.AssignmentName
        select e;

    var results =
        from person in students
        join entry in subquery on person.FullName equals entry.AuthorFullName into personEntries
        from personEntry in personEntries.DefaultIfEmpty()
        orderby person.FullName
        select new
        {
            PersonName = person.FullName,
            BlogTitle = personEntry == null ? "" : personEntry.Title
        };
}

使这更棘手的是你想要向所有学生展示,但只留下加入与博客作业匹配的博客条目,这是一个内部联接。

这就是为什么我添加了执行内连接的子查询,然后使用join..into语法在主查询中保持连接到该子查询,以获得左外连接语义。

您可以一次性完成所有操作,但我发现通过将子查询分解为单独的声明来更容易阅读LINQ查询。