linq从子集合中选择项目 [英] linq select items from child collection

查看:43
本文介绍了linq从子集合中选择项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的课程.我有一个包含日期列表的产品.每天都有一个城市财产.

Below are my classes. I have a product that contains list of days. Each day has a city property.

我需要创建一个linq查询,该查询将为我提供系统中所有产品上使用的不同城市.

I need to create a linq query that will give me the distinct cities that are used on all my products in the system.

我尝试了类似的方法,但是它不起作用:

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

推荐答案

您需要调用

You need to call the SelectMany function, which takes a single item and lets you get multiple items from it.

例如:

var cities = NHibernateSession.Linq<Product>()
                .SelectMany(p => p.Days)
                .Select(p => p.City)
                .Where(c => c != null)
                .Distinct();  

请注意,如果City类未正确实现EqualsGetHashCode,则将返回重复项.

Note that if the City class doesn't implement Equals and GetHashCode correctly, this will return duplicates.

您可以使用以下查询理解语法来做到这一点:(未经测试)

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();

这篇关于linq从子集合中选择项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆