C# List<T> lambda Find then Modify elements
15,333
Solution 1
Well, you could do:
list.FindAll(x => x.Seconds == 0)
.ForEach(x => x.Seconds = seconds);
Personally I'd prefer an explicit loop for the side-effecting part though:
foreach (var x in list.Where(x => x.Seconds == 0))
{
x.Seconds = seconds;
}
(I'm assuming this is a reference type, by the way. If it's a value type there are all kinds of other reasons why it wouldn't work.)
EDIT: You may wish to have a look at Eric Lippert's thoughts on the matter too.
Solution 2
list.FindAll(x => x.Seconds == 0)
.ForEach(x => x.Seconds = seconds);
I believe that the above does not compile.
.ForEach(...)
returns void which can not be on the right-hand side of the FindAll()
method.
Author by
Oneway
Updated on June 04, 2022Comments
-
Oneway almost 2 years
How would I go about doing this with a List using lambda
List<Foo> list....// create and add a bunch of Foo int seconds = 100; list.FindAll(x=>(x.Seconds == 0).Seconds = seconds) // yes I know that wont work...
In other words, find all of the foo objects that Seconds == 0 and change the value to my local variable...
I don't want to loop the list...I am sure there is a way to do this with a simple lambda method...
Any help appreciated
Oneway
-
Oneway about 14 yearsExcellent...thanks...in this case the top method works and seems the cleanest...basically all I am doing/need to do is take all of the items whose seconds == 0 in quick move...Dig that extension method ForEach...thanks
-
Jimmy over 13 yearsIn this case if I have indexes of the items to be modified, how should I write it?