C# linq 从子集合中选择项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2095263/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
linq select items from child collection
提问by GuestMVCAsync
Below are my classes. I have a product that contains list of days. Each day has a city property.
下面是我的课。我有一个包含天数列表的产品。每天都有一个城市属性。
I need to create a linq query that will give me the distinct cities that are used on all my products in the system.
我需要创建一个 linq 查询,该查询将为我提供系统中所有产品使用的不同城市。
I tried something like this but it does not work:
我试过这样的事情,但它不起作用:
var cities = from product in NHibernateSession.Linq<Product>() select new { city = product.Days.Where(d => d.City != null).Distinct() }; //This returns the day items but i need distinct cities
public class Product : EntityBase
{
public virtual string Name { get; set; }
public virtual IList<ProductDayDefinition> Days { get; set; }
}
public class ProductDayDefinition : EntityBase
{
public virtual Product Product { get; set; }
public virtual City City { get; set; }
}
采纳答案by SLaks
You need to call the SelectMany
function, which takes a single item and lets you get multiple items from it.
您需要调用该SelectMany
函数,该函数接受单个项目并让您从中获取多个项目。
For example:
例如:
var cities = NHibernateSession.Linq<Product>()
.SelectMany(p => p.Days)
.Select(p => p.City)
.Where(c => c != null)
.Distinct();
Note that if the City
class doesn't implement Equals
and GetHashCode
correctly, this will return duplicates.
请注意,如果City
类没有实现Equals
和GetHashCode
正确的,这将返回重复。
You can do this using query comprehension syntax like this: (Untested)
您可以使用这样的查询理解语法来做到这一点:(未经测试)
var cities = (from product in NHibernateSession.Linq<Product>()
from day in product.Days
where day.City != null
select day).Distinct();