为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

 

posted @ 2016-04-01 08:45  Insus.NET  阅读(653)  评论(0编辑  收藏  举报