开发者

LINQ: Transforming items in a collection

开发者 https://www.devze.com 2023-04-13 01:06 出处:网络
Is there a LINQ method to modify items in a collection, such as simply setting a property of each item in a collection?Something like this:

Is there a LINQ method to modify items in a collection, such as simply setting a property of each item in a collection? Something like this:

var items = new []{ new Item { 开发者_JS百科IsActive = true } }
var items = items.Transform(i => i.IsActive = false)

where Touch enumerates each item and applies the transformation. BTW, I am aware of the SELECT extension method, but this would require I expose a method on the type that does this transformation and return the same reference.

var items = items.Select(i => i.Transform())

where Item.Transform returns does the transformation and return the same instance.

TIA


No, there are no methods in standard LINQ that allows you to modify items in a collection. LINQ is for querying collections and not for causing side-effects (e.g., mutating the items). Eric Lippert goes into the idea in more detail in his blog post: “foreach” vs “ForEach”.

Just use a loop.

foreach (var item in items)
{
    item.IsActive = false;
}


LINQ is for querying. Use a simple loop if you want to modify. Just use the right tool for the right job. LINQ is not a messiah for everything.


There's a ForEach() on List, so you can do items.ToList().ForEach(i => i.IsActive = false). You might want to read this though.


The documentation page on MSDN for the Enumerable class lists all LINQ methods, and unfortunately no method there does what you want. LINQ is a query language and is not intended to modify collections. It is functional in its nature, meaning that it doesn't modify the collection it operates on, rather it returns a new enumerable.

For your purposes it is better to simply use a foreach loop, or if you feel the need write your own extension method to do what you want, eg.

public static void ForEach<T>(this IEnumerable<T> seq, Action<T> action)
{
   foreach (T item in seq)
      action(item);
}

which could then be used as you wanted:

items.ForEach(i => i.IsActive = false)
0

精彩评论

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

关注公众号