1

I have a collection of "product" objects that each contain a collection of benefit objects. See below:

<Products>
        <Product ID="454">
            <ProductName>Economy</ProductName>
            <Benefits>
                <Benefit>
                    <Name>Medical</Name>
                    <Value>5000000</Value>
                    <Excess>100</Excess>
                </Benefit>
                <Benefit>
                    <Name>Emergency</Name>
                    <Value>350</Value>
                    <Excess>100</Excess>
                </Benefit>
        </Product>
</Products>

I'm trying to create a LINQ query to get the "Medical" benefit value for product "454":

<%: Model.Products.Where(x => x.ProductId == "454").SelectMany(p => p.Benefits).Where(b => b.Name == "Medical").Select(v => v.Value.ToString()) %>

However this just returns:

System.Linq.Enumerable+WhereSelectEnumerableIterator`2[Domain.Entities.Benefit,System.String]  System.Linq.Enumerable+WhereSelectEnumerableIterator`2[Domain.Entities.Benefit,System.String]  System.Linq.Enumerable+WhereSelectEnumerableIterator`2[Domain.Entities.Benefit,System.String]  System.Linq.Enumerable+WhereSelectEnumerableIterator`2[Domain.Entities.Benefit,System.String

How do I get it to return the actual value I'm after?

0

3 Answers 3

4

If you know there is only one (guaranteed) then add .Single() - if there might be none / some and you just want the first, add .FirstOrDefault() (will return null if there are no results)

Sign up to request clarification or add additional context in comments.

1 Comment

If the collection might be empty also look into SingleOrDefault() or FirstOrDefault()
2

try this

Model.Products
    .Where(p => p.ID == 454)
    .SelectMany(p => p.Benefits)
    .Where(b => b.Name == "Medical")
    .Single()
    .Value.ToString();

Comments

0

try this:

var val = employees.Where(p => p.ProductId == 454).FirstOrDefault().Benefits.Select(b => b.Value).FirstOrDefault();

or

var benefits_value = employees.Where(p => p.ProductId == 454).Single().Benefits.Select(b => b.Value).Single();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.