Replace foreach with lambda while updating list

I want to update vmlist by geting values from vlist without using any foreach loop.

For now I am just doing this with foreach loop, but I want to replace this foreach with LINQ

foreach (var item in vlist){
    vmlist.Where(list => list.SId==item.SId && list.ParameterId==item.ParameterId && list.WId==item.WId)
    .Select(li => { li.Value = item.Value; return li; }).ToList();
}
Jon Skeet
people
quotationmark

Your current approach is very inefficient - it's O(N * M) and it creates a list on each iteration.

Using a join would be more efficient - I would still use a foreach loop, but separate the querying part from the update part:

var pairsToUpdate = from original in vmlist
                    join item in vlist
                      on new { original.SId, original.ParameterId, original.WId }
                      equals new { item.SId, item.ParameterId, item.WId }
                    select new { original, item };

foreach (var pair in pairsToUpdate)
{
    pair.original.Value = pair.item.Value;
}
  • No abuse of Select with side-effects
  • No extra lists created for no good reason
  • More efficient selection of items to update

people

See more on this question at Stackoverflow