Casey Crookston Casey Crookston - 1 month ago 7
C# Question

Filter a list in an inner foreach loop based on ID of outerloop

I have an outer and an inner foreach loop, each looping on a list. The inner loop needs to be filtered based on a current value of the outer loop. I need some help with the syntax of the where clause on the inner loop.

@foreach (var item1 in Model.list1)
{
...
@foreach (var item2 in Model.list2.Where( item2.item1id = item1.item1id ))
{
...
}
...
}


What is the correct syntax for that .Where statement?

Thanks!!

Answer

The way LINQ works in terms of these predicates is that you have to assign a variable as the element of list2 you are enumerating through, so the correct syntax would be:

@foreach (var item2 in Model.list2.Where(itemFromList2 => itemFromList2.item1id == item1.item1id))

As list is processed, Where assigns each item to itemFromList2 and uses that to compare.