Juanjo Juanjo - 29 days ago 16
C# Question

How to convert an expression to linq with nested foreach when the first element is being modified

I am having trouble on how to convert this to Linq. Any help will be greatly appreciated.

foreach (var stat in stats)
{
foreach (var record in worked)
{
if (stat.Name != record.Name) continue;
stat.WorkedToday = record.RecordCount;
break;
}
}

Answer

Please find an answer in .NET FIDDLE I hope this will help

//be careful method 'First' can throw an exception if there is no such element in sequence
stats
  .ForEach(s => s.WorkedToday = worked.First(w => w.Name == s.Name).RecordCount);
}