linq select items from child collection

前端 未结 1 1779
后悔当初
后悔当初 2021-01-17 07:27

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

相关标签:
1条回答
  • 2021-01-17 07:59

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

    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.

    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();
    
    0 讨论(0)
提交回复
热议问题