In the following code I’m using 3 foreach statements. I’m just looking to populate a list when a list of items matches another but the ones that don’t match also have to be added. So I was wondering if there is an easier way to do the following.
List<T> ds = new List<T>(); //is populated
foreach (var b in template.Bs)
{
List<BD> tempList = new List<BD>();
foreach (BD bd in b.BDs)
{
Boolean found = false;
foreach (DV dv in items)
{
if (bd.C == dv.C)
{
found = true;
tempList.Add(new BD ()
{
//populating
});
}
}
if (!found)
tempList.Add(new BD()
{
//populating
});
}
}
The relationship between
dsandtempListis not clear, but it looks to me like your inner loops are really a left outer join:For each
bintemplate.Bs, we’re matchingbd‘s fromb.BDswithdv‘s initems. We then useDefaultIfEmpty()to putnullindvif there was no match, which we then use to determine which projection method to call:NoMatch()would create a newBDbased on the unmatchedbd, andMatch()would create a newBDbased on the matchedbdanddv.That whole query is represented by
newBDs, which will beIEnumerable<BD>. We can then buffer that sequence intotempListor do something else useful with it.