Reputation: 41
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
Upvotes: 2
Views: 15962
Reputation: 11
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.
Upvotes: 1
Reputation: 1500035
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.
Upvotes: 11