很久沒碰 .net ,最近的小專案,剛好可以拿來磨磨這把已經銹掉的刀,回頭寫 Code 有點兒生疏,也有點兒熱血沸騰。
自從 .net 2.0 有了 Generic 之後,很多以前的 Array , ArrayList 都改用 List<T>,真是好用,
但是在搜尋 List<T> 中的物件,常常就需要寫 for... , foreach... 。 Predicate Delegate 可以簡化搜尋 List<T> ,應該是說可以更優雅的搜尋。
看一下下面的 Code,主要是第 2 ~ 5 行,只要回傳 bool 值就可以囉。
[copy code]
List<Category> _c = this.GetAllCategories(); List<Category> prod = _c.FindAll( delegate(Category c) { return c.Id == "3"; } ); //display foreach (Category c in prod) { Response.Write(c.Name); }
1: List<Category> _c = this.GetAllCategories();
2: List<Category> prod = _c.FindAll(
3: delegate(Category c)
4: { return c.Id == "3"; }
5: );
6: //display
7: foreach (Category c in prod)
8: {
9: Response.Write(c.Name);
10: }
這樣子寫也行,這樣子比較容易閱讀
[copy code]
_c = this.GetAllCategories(); List<Category> prod = _c.FindAll(GetId3); //display foreach (Category c in prod) { Response.Write(c.Name); } static bool GetId3(Category c) { if (c.Id=="3") return true; else return false; }
1: _c = this.GetAllCategories();
2: List<Category> prod = _c.FindAll(GetId3);
3: //display
4: foreach (Category c in prod)
5: {
6: Response.Write(c.Name);
7: }
8: static bool GetId3(Category c)
9: {
10: if (c.Id=="3")
11: return true;
12: else
13: return false;
14: }
不知道是不是自己太大驚小怪,還是坐井觀天,真的覺得 C# 真是個優雅的語言(小熊子沒仔細看 VB.net 不過 delegate 一定是 C# 比較美觀)。
可以用到的地方諸如:
Array.Find , Array.FindAll , Array.Exists , Array.FindLast , Array.FindIndex .....
List<T>.Find , List<T>.FindAll , List<T>.Exists , List<T>.FindLast , List<T>.FindIndex .....
在參考文章中,還有更特別的 C#3.0 Lambda Expressions,可以再將難懂的 delegate 再包裝一下,下次有空再仔細研究。
參考文章
MSDN:Predicate<(Of <(T>)>) Generic Delegate
The Predicate Delegate
Tags: .net