Using LINQ/Delegates, how to initialize a property belong to all the members of an Object of a type list?

StackOverflow https://stackoverflow.com/questions/23096694

This is the scenario:

//MyClass in a collection which makes MyObjects a list.
MyObjects = new ObservableCollection<MyClass>();

In this case if MyClass has a property called Arm, per say, how is it possible to initialize Arm property of all the members of MyObjects without iterating them inside Foreach loop like:

foreach (var MyObject in MyObjects)
{
    MyObject.Arm = "Manly"; 
}

I thought something like code below would be possible, but no

MyObjects.Select().Arm = "Manly";
有帮助吗?

解决方案

LINQ specifically does not have a "mutate all" method because it's trying to be kind of functional. If you absolutely must have this you can define your own ForEach extension method that takes an Action and runs it on all items.

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

This allows you to do

someObjects.ForEachAbomination(i => { i.Arm = "Manly"; });

But honestly, I think a foreach is more readable if you're mutating things.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top