Executing a certain action for all elements in an Enumerable

前端 未结 10 1742
春和景丽
春和景丽 2020-12-14 13:49

I have an Enumerable and am looking for a method that allows me to execute an action for each element, kind of like Select but then for si

10条回答
  •  -上瘾入骨i
    2020-12-14 14:39

    You cannot do this right away with LINQ and IEnumerable - you need to either implement your own extension method, or cast your enumeration to an array with LINQ and then call Array.ForEach():

    Array.ForEach(MyCollection.ToArray(), x => x.YourMethod());
    

    Please note that because of the way value types and structs work, if the collection is of a value type and you modify the elements of the collection this way, it will have no effect on the elements of the original collection.

提交回复
热议问题