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).
Where(w => w.Name == "height"). Select(s => { s. Value = 30; return s; }). ToList();
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!
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With