带连接的linq查询

时间:2011-08-10 20:24:31

标签: c# .net linq collections

我无法准备我需要的查询。我有代码:

public class Dog
{
    public int id;
    public int? OwnerID;
    public string name;
}

public class Person
{
    public int id;
    public string Name; 
}

public class Group
{
    public Dog dog;
    public Person owner;
}
class Program
{
    static void Main(string[] args)
    {
        IEnumerable<Dog> dogs = new[] { 
                                        new Dog { id = 1, OwnerID = null, name = "Burke" }, 
                                        new Dog { id = 2, OwnerID = 2, name = "Barkley" } 
                                      };
        IEnumerable<Person> owners = new[] { 
                                               new Person { id = 1, Name = "Jack" },
                                               new Person { id = 2, Name = "Philip" }
                                            };

        var groups = from dog in dogs
                     join owner in owners on dog.OwnerID equals owner.id
                     select new Group
                     {
                         dog = dogs.First(d => d.id == dog.id),
                         owner = owners.First(o => o.id == owner.id)
                     };
        foreach (var g in groups)
        {
            var text = g.dog.name + " belongs to " + (g.owner == null ? "no one" : g.owner.Name);
            Console.WriteLine(text);
        }
        Console.ReadLine();
    }
}

并且它无法正常工作。如何准备查询,即使Dog对象中的OwnerID为null,仍然会创建新的Group实例并将其添加到groups变量中?

2 个答案:

答案 0 :(得分:3)

喜欢这样

var groups = from dog in dogs
join owner in owners on dog.OwnerID equals owner.id
from own in owner.DefaultIfEmpty()
select new Group
{
  dog = dogs.First(d => d.id == dog.id),
  owner = own.First(o => o.id == owner.id)
};

请参阅http://smehrozalam.wordpress.com/2009/06/10/c-left-outer-joins-with-linq/

尽管他的例子显示了对SQL的翻译,但同样适用于linq to objects

答案 1 :(得分:1)

根据您的描述,听起来您想对狗进行左外连接查询。 查看Microsoft的LINQ示例中的example,了解如何使用DefaultIfEmpty() LINQ函数。