tags:

views:

64

answers:

3

I have the following that selects a list of benefits for a given product:

foreach (var benefit in Model.Products.Where(x => x.ProductId == "454").SelectMany(p => p.Benefits).Where(b => b.HeadlineBenefit == false))

However I want to change this to select a list of befits for the first product in the collection. I thought the below would work but it doesnt:

foreach (var benefit in Model.Products.FirstOrDefault().SelectMany(p => p.Benefits).Where(b => b.HeadlineBenefit == false))
A: 
    foreach (var benefit in Model.Products
.Where(b => b.HeadlineBenefit == false).FirstOrDefault()) {
    //work
    }

how about something like that?

bluevoodoo1
+1  A: 

Given that FirstOrDefault() isolates a single product, you don't need SelectMany(), for example:

foreach (var benefit in Model.Products.FirstOrDefault().Benefits.Where(b => b.HeadlineBenefit == false))
Edgar Sánchez
Im trying to isolate a single product but do a select many on the benefits of that product.
StephenLewes
OK, sorry for my omition, then the sequence could be: Model.Productos.Single(p => p.Id == "123").Benefits.Where(b => /* b cond. */);
Edgar Sánchez
A: 

Are you trying to get all of the benefits for the first product?

If so you could do the following:

//get a product that has at least one benefit matching our criteria
var product = Model.Products.Where(m => m.Benefits.Any(b => !b.HeadlineBenefit)).FirstOrDefault();

//now do something with all of the benefits that match our criteria
foreach (var benefit in product.Benefits.Where(b => !b.HeadlineBenefit))

Note how I've used the criteria into both queries. If you just grab the first product it could have no applicable benefits!

DoctaJonez