扩展IEnumerable<T> ForEach()方法

本文介绍了一种在Linq中为IEnumerable<T>类型添加ForEach方法的实现方式,通过定义扩展方法使IEnumerable<T>具备遍历功能,提高了代码的可读性和便捷性。
 

    相信很多人,在用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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值