简体   繁体   English

Linq多次选择查询与Distinct

[英]Linq many to many select query with Distinct

I have the following models: 我有以下型号:

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; }
}

A Person can have many hobbies, and vice Versa, and a Person can have a single Location. 一个人可以有很多爱好,副Versa,一个人可以有一个位置。

I'd like to do a query that for a given Location returns all the distinct Hobbies from the people in that Location 我想查询一个给定位置返回该位置中人员的所有不同爱好

So if the location is "Dallas", find all the people in Dallas, return all their Hobbies, and remove the duplicates. 因此,如果位置是“达拉斯”,找到达拉斯的所有人,返回他们所有的爱好,并删除重复。

You can try this way : 你可以这样试试:

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

you have the relationship well represented using FKs, so you can simplify your query like this: 您使用FK很好地表示了这种关系,因此您可以像这样简化查询:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM