Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change some value inside the List<T>

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

like image 964
Mitja Bonca Avatar asked Oct 20 '12 08:10

Mitja Bonca


People also ask

How to change specific value in list c#?

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

Why does adding a new value to List <> overwrite previous values in the list <>?

Essentially, you're setting a Tag's name to the first value in tagList and adding it to the collection, then you're changing that same Tag's name to the second value in tagList and adding it again to the collection. Your collection of Tags contains several references to the same Tag object!


1 Answers

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); 
like image 142
McGarnagle Avatar answered Sep 18 '22 07:09

McGarnagle