开发者

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

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜