需 VS2005 + LINQ Preview。命令行編譯參考:
csc.exe /reference:System.Data.DLinq.dll /reference:System.Query.dll ...
雙擊 AnonMethod 看到編譯器生成的狀態機結構:
<>9__CachedAnonymousMethodDelegate1<AnonMethod>b__0List.FindAll 調用委托過濾結論:Lambda 與匿名方法編譯目標一致,Lambda 只是更簡潔的語法糖。
// 顯式類型
(int x, int y) => x + y
// 隱式類型(推薦)
(x, y) => x * y
var clothes = new Dictionary
{
{"Jeans", 20}, {"Shirts", 15}, {"Pajamas", 9}, {"Shoes", 9}
};
// 擴展方法 FilterBy
var shortage = clothes.FilterBy((name, count) => name == "Shoes" && count < 10);
// shortage 為 Dictionary,僅含 {"Shoes", 9}
if (shortage.Count > 0)
Console.WriteLine("We are short of shoes");
public delegate bool KeyValueFilter(K key, V value);
public static class Extensions
{
public static Dictionary FilterBy(
this Dictionary items,
KeyValueFilter filter)
{
var result = new Dictionary();
foreach (var kvp in items)
if (filter(kvp.Key, kvp.Value))
result.Add(kvp.Key, kvp.Value);
return result;
}
}
Lambda 表達式支持多參數(顯式/隱式類型),編譯器生成與匿名方法等價 IL。配合擴展方法,可為 Dictionary 等類型添加流式過濾能力,代碼簡潔且強類型安全。