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 cr开发者_开发技巧eate 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?
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)
try this
Model.Products
.Where(p => p.ID == 454)
.SelectMany(p => p.Benefits)
.Where(b => b.Name == "Medical")
.Single()
.Value.ToString();
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();
精彩评论