Smith
Smith

Reputation: 3164

Need some help on a somewhat complex LINQ query

I have this query that does what I want which is to return true if any of the materials is comparable in the material groups list.

mgroup.MaterialGroups.Select(x => x.Materials
                                   .Any(m => Convert.ToBoolean(m.Comparable)))
                                   .Any(x => x.Equals(true))

What I would like to add to this query is to also include this one.

mgroup.Materials.Any(m => Convert.ToBoolean(m.Comparable));

How can I combine mgroup and it's materialgroups together in the query so I can select both of their Materials? Thanks.

EDIT - After fighting with LINQ for awhile I broke down and just combined as

mgroup.Materials.Any(m => Convert.ToBoolean(m.Comparable) || 
mgroup.MaterialGroups.Select(x => x.Materials
                     .Any(c => Convert.ToBoolean(c.Comparable)))                                                                                                                                   
                     .Any(x => x.Equals(true)))  

It works as expected but it's horribly long and it's embedded in an Asp.net MVC view to makes things even worse. If anyone can simplify this that would be amazing.

P.S.- If you are wondering why I added the extra .Any(x => x.Equals(true) at the end it's because without it the query returns an IEnumerable of bools instead of bool.

Upvotes: 0

Views: 50

Answers (1)

vc 74
vc 74

Reputation: 38179

IEnumerable<Material> allMaterials = 
                      mgroup.Materials.Concat(
                      mgroup.MaterialGroups.SelectMany(group => group.Materials));
bool result = allMaterials.Any(m => Convert.ToBoolean(m.Comparable));

Upvotes: 1

Related Questions