开发者

Simple Transformation with Linq

I'm sure this is a trivial question but I couldn't fin开发者_StackOverflow中文版d a good example. Suppose all you want to do is change one attribute for all objects in a list. I'd like to say something like:

List<SomeType> list = ...;

list.Select(x => x { x.Name = "Foo" } );

Notice the absence of the "new" keyword. I don't want to recreate objects that already exist, just execute one line of code (in this case a simple assignment) on every element of the list.

Is this possible in linq in some elegant way?

Thanks in advance!


Very easy. MSDN ForEach its actually just a method of the List class, but it allows for you to use Lambda expressions.

 list.Foreach(x => x.Name = "Foo"  );


It doesn't really fall under Linq if you want to mutate the collection. See Eric Lippert's post to see why.

Try List<T>.ForEach()

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜