1. 什么是LINQ
2. 扩展方法
3. Lambda 表达式
4. LINQ查询的两种语法
LINQ
LINQ Architecture
this
关键词using
— 例子来自MSDN
首先,定义一个扩展方法
namespace ExtensionMethods
{
public static class MyExtensions
{
public static int WordCount(this String str)
{
return str.Split(new char[] { \' \', \'.\', \'?\' },
StringSplitOptions.RemoveEmptyEntries).Length;
}
}
}
调用刚刚写好的扩展方法
using ExtensionMethods;
string s = \"Hello Extension Methods\";
int i = s.WordCount();
/*
output: 3
*/
System.Linq
命名空间中的内建扩展方法=>
(input parameters) => expression
n => n % 2 == 0
List numbers = new List{1, 3, 5, 6, 8};
List evenNumbers = numbers.where(n => n % 2 == 0).ToList();
/*
evenNumbers = {6, 8}
*/
如果没有LINQ,将使用的方法如下
public static void OldSchoolSelectOne()
{
List names = new List
{
\"Andy\", \"Bill\", \"Dani\", \"Dane\"
};
string result = string.Empty;
foreach (string name in names)
{
if (name == \"Andy\")
{
result = name;
}
}
Console.WriteLine(\"We found \" + result);
}
使用LINQ,两种方法如下
// Method syntax
public static void Single()
{
List names = new List
{
\"Andy\", \"Bill\", \"Dani\", \"Dane\"
};
string name = names.Single(n => n == \"Andy\");
Console.WriteLine(name);
}
//
// Query syntax
public static void Single()
{
List names = new List
{
\"Andy\", \"Bill\", \"Dani\", \"Dane\"
};
string name = from name in names
where name = \"Andy\"
select name;
Console.WriteLine(name);
}
上一篇:ASP.NET Razor 简介
下一篇:ASP.NET Razor 简介