1. 什么是LINQ
2. 扩展方法
3. Lambda 表达式
4. LINQ查询的两种语法
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<int> numbers = new List<int>{1, 3, 5, 6, 8};
List<int> evenNumbers = numbers.where(n => n % 2 == 0).ToList();
/*
evenNumbers = {6, 8}
*/
如果没有LINQ,将使用的方法如下
public static void OldSchoolSelectOne()
{
List<string> names = new List<string>
{
"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<string> names = new List<string>
{
"Andy", "Bill", "Dani", "Dane"
};
string name = names.Single(n => n == "Andy");
Console.WriteLine(name);
}
//
// Query syntax
public static void Single()
{
List<string> names = new List<string>
{
"Andy", "Bill", "Dani", "Dane"
};
string name = from name in names
where name = "Andy"
select name;
Console.WriteLine(name);
}
2024 - 快车库 - 我的知识库 重庆启连科技有限公司 渝ICP备16002641号-10
企客连连 表单助手 企服开发 榜单123