為IEnumerable擴展一個ForEach方法,ienumerableforeach
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