为IEnumerable扩展一个ForEach方法

IEnumerable没有一个ForEach方法,我们可以使用C#写一个扩展方法:


Source Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Insus.NET.ExtendMethods
{
  public static class Enumerables
    {        
        public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
        {
            foreach (T item in source)
            {
                action(item);
            }
        }
    }
}
View Code

 

下例中,Insus.NET列举一个IEnumerable数据集,然后使用这个方法来获取其中的元素:


Source Code:

public IEnumerable<IDictionary<string, object>> Links()
        {
            var dict = new Dictionary<string, object>();
            dict["Index"] = "新产品介绍";
            dict["Manufacturing"] = "制造能力/流程";
            dict["DieCasting"] = "压铸";
            dict["Machining"] = "加工";
            dict["AssemblyFinishing"] = "组装&成品";
            dict["TestReliability"] = "测试和可靠性";
            dict["KeyCustomer"] = "关键客户";
            yield return dict;
        }
View Code

 

ForEach方法应用:

 

Source Code:

obj.Links().ForEach(delegate (IDictionary<string, object> dict) {
            foreach (KeyValuePair<string, object> kvp in dict)
            {
                    //kvp.Key
                    //kvp.Value
            }
        });
View Code

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值