扩展IEnumerable<T> ForEach()方法

 

    相信很多人,在用Linq时,都会困惑为什么IEnumerabel<T>没有ForEach,虽然 我们一样可以这样写,很快读写

foreach(item in items)
{
  Console.Write(item);
}
但是相信总有人,会感觉不平衡吧,List<T> 就可以很轻松的ForEach()就可以.而此时不行.很是失望吧.
呵呵.添加如下代码扩展方法,申明在空间 System.Linq 下.这样你就在直接调用IEnumerable<T>.ForEach().
namespace System.Linq;
{
    public static class EnumerableExtensionMethods
    {
        public static IEnumerable<T> ForEach<T>(this IEnumerable<T> source, Action<T> action)
        {
            if (action == null)
                throw new ArgumentNullException("action");

            foreach (var item in source)
                action(item);

            return source;
        }
    }
}
 
 
原文地址:https://www.cnblogs.com/lvdongjie/p/5590035.html