Have a look to the following example:
The first solution, using the foreach, works pretty well and easily. But I was trying to write it using Linq and I could not achieve this result. I made some attempts but no one succeeded.
I expect to find just one element.
The problem is not at runtime: I don't know very well the Linq sintax and so I don't know how to get the element called PlacedSelection (the foreach structure clarifies where I'm looking for it). Instead in my attempt I could get the PlacedCategory elements.. but I don't need this..
PlacedSelection ActualSelection = null;
foreach (var placedCategory in Model.Coupon.Categories)
{
foreach (PlacedSelection placedSelection in placedCategory.Value.Selections)
{
var pp = placedSelection.EventId;
if (pp == Model.EventId)
{
ActualSelection = placedSelection;
break;
}
}
}
//IEnumerable<KeyValuePair<string, PlacedCategory>> p = Model.Coupon.Categories(c => c.Value.Selections.Any(s=> s.EventId == Model.EventId));
It looks like you want:
PlacedSelection actualSelection = Model.Coupon.Categories
.SelectMany(cat => cat.Value.Selections)
.FirstOrDefault(selection => selection.EventId == Model.EventId);
Any
would be used if you were trying to find the category, but you're trying to find the selection, by the looks of it.
See more on this question at Stackoverflow