Executing a certain action for all elements in an Enumerable

前端 未结 10 1740
春和景丽
春和景丽 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:40

    As mentioned before ForEach extension will do the fix.

    My tip for the current question is how to execute the iterator

    [I did try Select(s=> { Console.WriteLine(s); return s; }), but it wasn't printing anything.]

    Check this

    _= Names.Select(s=> { Console.WriteLine(s); return 0; }).Count();

    Try it!

    0 讨论(0)
  • 2020-12-14 14:43

    Using Parallel Linq:

    Names.AsParallel().ForAll(name => ...)

    0 讨论(0)
  • 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<T> ForEach<T>(this IEnumerable<T> _this, Action<T> del)
        {
            List<T> list = _this.ToList();
            list.ForEach(del);
            return list;
        }
    }
    
    0 讨论(0)
  • 2020-12-14 14:51

    Because LINQ is designed to be a query feature and not an update feature you will not find an extension which executes methods on IEnumerable<T> because that would allow you to execute a method (potentially with side effects). In this case you may as well just stick with

    foreach(string name in Names)
    Console.WriteLine(name);

    0 讨论(0)
提交回复
热议问题