Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set property for each item in collection

I have an IEnumerable and I try to call "Text" setter in each item of the enumerable.
I can do:

foreach (Data d in DataEnumerable)
{
    d.Text="123";
}

I can also do:

DataEnumerable.All(x =>
    {
        x.Text = "123";
        return true;
    });

What is the best practice to call set method for each item of enumerable?

like image 960
Naor Avatar asked Dec 27 '22 13:12

Naor


1 Answers

The first method is better.

The second is an abuse of Enumerable.All. This method is intended to be used to test all elements of an Enumerable to see if they satisfy a condition. You are not doing that here.

There is a method List.ForEach which can be used for this sort of update operation, but the LINQ team decided not to add a corresponding method in Enumerable. See Eric Lippert's blog for details on why this decision was made:

  • "foreach" vs "ForEach"
like image 156
Mark Byers Avatar answered Jan 11 '23 13:01

Mark Byers