Change some value inside the List<T>

Mitja Bonca picture Mitja Bonca · Oct 20, 2012 · Viewed 184.6k times · Source

I have some list (where T is a custom class, and class has some properties). I would like to know how to change one or more values inside of it by using Lambda Expressions, so the result will be the same as the foreach loop bellow:

NOTE: list contains multiple items inside (multiple rows)

        foreach (MyClass mc in list)  
        {
            if (mc.Name == "height")
                mc.Value = 30;
        }

And this the the linq query (using Lambda expressions), but its not the same as the upper foreach loop, it only returns 1 item (one row) from the list!

What I want is, that it returns all the items (all rows) and ONLY changes the appropriate one (the items specified in the WHERE extension method(s).

list = list.Where(w => w.Name == "height").Select(s => { s.Value = 30; return s; }).ToList();

NOTE: these 2 example are not the same! I repeat, the linq only returns 1 item (one row), and this is something I don't want, I need all items from the list as well (like foreach loop, it only do changes, but it does not remove any item).

Answer

McGarnagle picture McGarnagle · Oct 20, 2012

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);