星期三, 6月 24, 2009

IEnumerable 的 Foreach

話說阿..程式寫久了,就開始懶了,能短的就給他短,能少的一定不會給他多..今天就在處理 IEnumerable 物件時,就找一下看有沒有Foreach這函式可以用..找半天..咪有..Confused..哇哩勒..這好用的東西沒得用..索性就給他寫一個..

public static class Helper
{
public static void Foreach<T>(this IEnumerable<T> source, Action<T> action)
{
foreach (var a in source)
{
action(a);
}
}
}

使用前~

using (NORTHWNDModel.NORTHWNDEntities db = new NORTHWNDModel.NORTHWNDEntities())
{
List<string> listArr = new List<string>();
var aaaa = db.Orders.Select(a => a.ShipName).Take(5);
//要用 foreach 跑跑跑
foreach (var a in aaaa)
{
listArr.Add(a);
}
Response.Write(string.Join("<br />", listArr.ToArray()));
}

使用後~

using (NORTHWNDModel.NORTHWNDEntities db = new NORTHWNDModel.NORTHWNDEntities())
{
List<string> listArr = new List<string>();
var aaaa = db.Orders.Select(a => a.ShipName).Take(5);
//用寫好的去跑
aaaa.Foreach(a => { listArr.Add(a); });
Response.Write(string.Join("<br />", listArr.ToArray()));
}

哈..看起來好像沒啥差..Embarrassed..不過寫起來感覺好很多..給各位參考啦..

參考:

1 則留言:

提到...

List< string> myList = db.Orders.Select(a => a.ShipName).Take(5).ToList();
或著
string str = string.Join(",", db.Orders.Select(a => a.ShipName).Take(5).ToArray());