开发者

Set property for each item in collection

开发者 https://www.devze.com 2023-04-12 06:00 出处:网络
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)

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;
    });

Wh开发者_JAVA技巧at is the best practice to call set method for each item of enumerable?


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"
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号