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(this IEnumerable source, Action action) { foreach (T item in source) { action(item); } } }}
下例中,Insus.NET列举一个IEnumerable数据集,然后使用这个方法来获取其中的元素:
Source Code:public IEnumerable> Links() { var dict = new Dictionary (); dict["Index"] = "新产品介绍"; dict["Manufacturing"] = "制造能力/流程"; dict["DieCasting"] = "压铸"; dict["Machining"] = "加工"; dict["AssemblyFinishing"] = "组装&成品"; dict["TestReliability"] = "测试和可靠性"; dict["KeyCustomer"] = "关键客户"; yield return dict; }
ForEach方法应用:
Source Code:
obj.Links().ForEach(delegate (IDictionarydict) { foreach (KeyValuePair kvp in dict) { //kvp.Key //kvp.Value } });