Linq多对多选择查询与Distinct

本文关键字:Distinct 查询 选择 Linq | 更新日期: 2023-09-27 17:50:38

我有以下模型:

public class Person
{
    public string fullName { get; set; }
    public virtual ICollection<Hobby> hobbies { get; set; }
    public virtual Location location { get; set; }
}
public class Hobby
{
    public string hobbyName { get; set; }
    public virtual ICollection<Person> people { get; set; }           
}
public class Location
{
   public string locationName { get; set; }
   public virtual ICollection<Person> People { get; set; }
}

一个人可以有很多爱好,反之亦然,一个人可以有一个单一的位置。

我想做一个查询,对于给定的位置,返回该位置中所有人的不同爱好

如果位置为"Dallas",则查找达拉斯的所有人,返回他们的所有爱好,并删除重复项。

Linq多对多选择查询与Distinct

您可以这样尝试:

var hobbies = (from h in hobbies
                where h.people.Any(p => p.location.locationName == "Dallas")
                select h);

您已经使用fk很好地表示了关系,因此您可以像这样简化您的查询:

from p in persons 
Where p.location.locationName = "London"
select new 
{
    person = p,
    hobbies = p.hobbies
}