注意事项:
1) 前提是开发者机器要装有Framework 3.5, 引入Reference : System.Core
2) 若发布服务器没装 Framework 3.5, 需手工把 System.Core.dll 加入到 bin 下再发布
===========================================
using System.Linq;
..
string[] list = new string[] { "mary", "tom", "david", "cathy", "tom" }; // 除数组外, 其它集合类也可 (如: List, Hashtable , Dictionary)
IEnumerable<string> result;
//
Console.WriteLine("--- 'FirstOrDefault' --");
result = Enumerable.Where<string>(list,
delegate(string item)
{
return item == "tom";
});
Console.WriteLine(Enumerable.FirstOrDefault(result));
//
Console.WriteLine("--- 'OrderBy' --");
result = Enumerable.OrderBy<string, string>(list,
delegate(string item)
{
return item;
});
foreach (string str in result)
{
Console.WriteLine(str);
}
//
Console.WriteLine("--- 'Min' --");
string result_str = Enumerable.Min<string, string>(list,
delegate(string item)
{
return item;
});
Console.WriteLine(result_str);
//
Console.WriteLine("--- 'Distinct' --");
result = Enumerable.Distinct<string>(list);
foreach (string str in result)
{
Console.WriteLine(str);
}
//
Console.WriteLine("--- 'All' --");
bool result_bool = Enumerable.All<string>(list, delegate(string item)
{
return item.CompareTo("d") > 0;
});
Console.WriteLine(result_bool);
//
Console.WriteLine("--- 'Distinct' & 'OrderBy' & 'Where' --");
result = Enumerable.Distinct<string>(Enumerable.OrderBy<string, string>(Enumerable.Where<string>(list,
delegate(string item)
{
return item == "tom" || item == "david";
}),
delegate(string item)
{
return item;
}));
foreach (string str in result)
{
Console.WriteLine(str);
}
===========================================
输出如下:
--- 'FirstOrDefault' --
tom
--- 'OrderBy' --
cathy
david
mary
tom
tom
--- 'Min' --
cathy
--- 'Distinct' --
mary
tom
david
cathy
--- 'All' --
False
--- 'Distinct' & 'OrderBy' & 'Where' --
david
tom