Executing a certain action for all elements in an Enumerable

前端 未结 10 1746
春和景丽
春和景丽 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条回答
  •  既然无缘
    2020-12-14 14:47

    There is a ForEach method off of List. You could convert the Enumerable to List by calling the .ToList() method, and then call the ForEach method off of that.

    Alternatively, I've heard of people defining their own ForEach method off of IEnumerable. This can be accomplished by essentially calling the ForEach method, but instead wrapping it in an extension method:

    public static class IEnumerableExtensions
    {
        public static IEnumerable ForEach(this IEnumerable _this, Action del)
        {
            List list = _this.ToList();
            list.ForEach(del);
            return list;
        }
    }
    

提交回复
热议问题