经典收藏dotNET

ASP.NET LINQ 简介

2015-06-21  本文已影响425人  Jason_Yuan

目录###

1. 什么是LINQ
2. 扩展方法
3. Lambda 表达式
4. LINQ查询的两种语法


LINQ

1. 什么是LINQ ?

LINQ Architecture

2. 扩展方法(Extension Method)

2.1 扩展方法的特性

2.2 扩展方法实例

-- 例子来自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
*/

2.3 System.Linq命名空间中的内建扩展方法


3. Lambda 表达式

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}
*/

***

# 4. LINQ查询的两种语法
* **Query syntax**(查询语句语法)
更接近于SQL的语法
* **Method syntax**(查询方法语法)
主要利用 System.Linq.Enumerable 类中定义的扩展方法和Lambda 表达式方式进行查询
* LINQ可以使用于List<T>, Array, Dictionary<TKey, TValue>, string......

如果没有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);
}


***

# 参考资料和扩展阅读
1. [LINQ Introduction Part 1 Of 3](http://www.codeproject.com/Articles/18116/LINQ-Introduction-Part-Of#WhatItsNot)
2. [Introducing LINQ—Language Integrated Query](http://www.codeproject.com/Articles/199060/Introducing-LINQ-Language-Integrated-Query)
3. [LINQ Tutorial for Beginners](http://www.codeproject.com/Tips/590978/LINQ-Tutorial-for-Beginners)
4. [Understanding LINQ (C#)](http://www.codeproject.com/Articles/19154/Understanding-LINQ-C)
5. [What is Linq and what does it do?](http://stackoverflow.com/questions/471502/what-is-linq-and-what-does-it-do)
6. [Linq语法详细](http://blog.csdn.net/ycwol/article/details/42102939)
7. [LINQ tutorial](https://www.youtube.com/watch?v=z3PowDJKOSA&list=PL6n9fhu94yhWi8K02Eqxp3Xyh_OmQ0Rp6) 
8. [101 LINQ Samples](https://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b)
上一篇下一篇

猜你喜欢

热点阅读