我有这个数据结构:
class Person
{
public string FirstName { get; set; }
}
class Pet
{
public int Id { get; set; }
public string Name { get; set; }
}
class Link
{
public Person Person { get; set; }
public int PetId { get; set; }
}
和这个数据:
List<Person> people = new List<Person>
{
new Person {FirstName = "Foo"},
new Person {FirstName = "Bar"}
};
List<Pet> pets = new List<Pet>
{
new Pet {Id = 1, Name = "FooBoy"},
};
List<Link> links = new List<Link>
{
new Link {Person = people.First(), PetId = pets.First().Id}
};
现在我要获取所有人及其宠物名称的列表(如果没有宠物,则为null) 结果应该是
Foo - FooBoy
Bar - null
我试过
var query = from person in people
join lnk in links on person equals lnk.Person into linkPets
from link in linkPets.DefaultIfEmpty()
join p in pets on link.PetId equals p.Id into subPets
from subPet in subPets.DefaultIfEmpty()
select new { person.FirstName, PetName = (subPet == null ? String.Empty : subPet.Name) };
但我在link.Pet
上得到空引用异常。如果我删除linkPets.DefaultIfEmpty()
,我只会获得第一个人。
答案 0 :(得分:2)
在问题发生变化之前
(最初链接表引用了宠物,而不是ID。)
在我看来,你只需要一个连接,因为你可以使用链接中的Pet
属性,其中有一个:
var query = from person in people
join lnk in links on person equals lnk.Person into linkPets
from link in linkPets.DefaultIfEmpty()
select new { person.FirstName,
PetName = link == null ? "" : link.Pet.Name };
问题改变后
我已经离开了上面的原始解决方案,因为很容易将修改后的问题转换为原始问题 - 只需先在pets
和links
之间进行联接:
var fullLinks = from link in links
join pet in pets on link.PetId equals pet.Id
select new { link.Person, Pet = pet };
var query = from person in people
join lnk in fullLinks on person equals lnk.Person into linkPets
from link in linkPets.DefaultIfEmpty()
select new { person.FirstName,
PetName = link == null ? "" : link.Pet.Name };
如果你愿意,可以在一个声明中完成,但我不会:
var query = from person in people
join lnk in (from link in links
join pet in pets on link.PetId equals pet.Id
select new { link.Person, Pet = pet } )
on person equals lnk.Person into linkPets
from link in linkPets.DefaultIfEmpty()
select new { person.FirstName,
PetName = link == null ? "" : link.Pet.Name };
答案 1 :(得分:1)
如果你想通过链接表获得人和宠物,你可以这样做:
var result= (
from person in people
from lnk in links
.Where (w =>w.Person==person).DefaultIfEmpty()
from p in pets
.Where (w =>w==(lnk==null?null:lnk.Pet)).DefaultIfEmpty()
select new { person.FirstName, PetName = (p == null ? String.Empty : p.Name) }
).Dump();
答案 2 :(得分:1)
另一个解决方案是使用linkPets.DefaultIfEmpty(new Link())(可能只适用于加入内存,因为您的原始加入适用于数据库)
var query = from person in people
join lnk in links on person equals lnk.Person into linkPets
from link in linkPets.DefaultIfEmpty(new Link())
join p in pets on link.PetId equals p.Id into subPets
from subPet in subPets.DefaultIfEmpty()
select new { person.FirstName, PetName = (subPet == null ? String.Empty : subPet.Name) };