C# 3.0新特性体验之Lambda表达式
【IT168 技术文档】
假设你需要创建一个按钮,当点击它的时候更新ListBox里的内容。在C#1.0和1.1里,你要这样做:
在C#2.0里,你需要这样做:
// Program.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Query;
using System.XML.XLinq;
using System.Data.DLinq;
namespace LambdaExample

...{
public delegate bool KeyValueFilter<K, V>(K key, V value);
static class Program

...{
static void Main(string[] args)

...{
List<string> list = new List<string>();
list.Add("AA");
list.Add("ABC");
list.Add("DEFG");
list.Add("XYZ");
Console.WriteLine("Through Anonymous method");
AnonMethod(list);
Console.WriteLine("Through Lambda expression");
LambdaExample(list);
Dictionary<string, int> varClothes= new Dictionary<string,int>();
varClothes.Add("Jeans", 20);
varClothes.Add("Shirts", 15);
varClothes.Add("Pajamas", 9);
varClothes.Add("Shoes", 9);
var ClothesListShortage = varClothes.FilterBy((string name,
int count) => name == "Shoes" && count < 10);
// example of multiple parameters
if(ClothesListShortage.Count > 0)
Console.WriteLine("We are short of shoes");
Console.ReadLine();
}
static void AnonMethod(List<string> list)

...{
List<string> evenNumbers = list.FindAll(delegate(string i)

...{ return (i.Length % 2) == 0; });
foreach (string evenNumber in evenNumbers)

...{
Console.WriteLine(evenNumber);
}
}
static void LambdaExample(List<string> list)

...{
var evenNumbers = list.FindAll(i =>(i.Length % 2) == 0);
// example of single parameter
foreach(string i in evenNumbers)

...{
Console.WriteLine(i);
}
}
}
public static class Extensions

...{
public static Dictionary<K, V> FilterBy<K, V>
(this Dictionary<K, V> items, KeyValueFilter<K, V> filter)

...{
var result = new Dictionary<K, V>();
foreach(KeyValuePair<K, V> element in items)

...{
if (filter(element.Key, element.Value))
result.Add(element.Key, element.Value);
}
return result;
}
}
}