Change some value inside the List<T>
You could use ForEach
, but you have to convert the IEnumerable<T>
to a List<T>
first.
list.Where(w => w.Name == "height").ToList().ForEach(s => s.Value = 30);
I'd probably go with this (I know its not pure linq), keep a reference to the original list if you want to retain all items, and you should find the updated values are in there:
foreach (var mc in list.Where(x => x.Name == "height"))
mc.Value = 30;
You could use a projection with a statement lambda, but the original foreach
loop is more readable and is editing the list in place rather than creating a new list.
var result = list.Select(i =>
{
if (i.Name == "height") i.Value = 30;
return i;
}).ToList();
Extension Method
public static IEnumerable<MyClass> SetHeights(
this IEnumerable<MyClass> source, int value)
{
foreach (var item in source)
{
if (item.Name == "height")
{
item.Value = value;
}
yield return item;
}
}
var result = list.SetHeights(30).ToList();