28

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.

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

1 Answer 1

58

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(); 
Sign up to request clarification or add additional context in comments.

2 Comments

When my Property equivalent to Days is null in all my equivalent Product Class Objects, I get a 'System.NullReferenceException'. How do I avoid that Exception (i.e. without first explicitly (i.e. via a separate Statement) scanning Product Class Objects first to ensure at least one has a non-null Days Property)? Hoping for something like a Null Conditional Operator.
@Tom: Either add where product.Days != null first or add ?? Enumerable.Empty<T>(). I don't know how that would work with a query provider, though.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.