LINQ表达式简单描述

在向大家详细介绍LINQ表达式之前,首先让大家了解下LINQ表达式简介,然后全面介绍LINQ表达式。

LINQ表达式简介

1.OO(面向对象)以外的疆域:信息的访问与整合。关系数据库与XML为其中的典型应用。

2.NET Language Integrated Query (LINQ):不采用特定於关系数据库或者XML的专有方案,而采用通用方案来解决各种信息源的访问与整合问题。

3.在LINQ中,查询成为编程语言的一个组成部分,这使得查询表达式可以得到很好的编译时语法检查,丰富的元数据,智能感知等强类型语言的好处。

初识LINQ表达式

 
 
 
  1. class app {  
  2. static void Main() {  
  3. string[] names = { "Burke", "Connor", "Frank",  
  4. "Everett", "Albert", "George",  
  5. "Harris", "David" };  
  6. IEnumerable<string> query = from s in names  
  7. where s.Length == 5  
  8. orderby s  
  9. select s.ToUpper();  
  10. foreach (string item in query)  
  11. Console.WriteLine(item);  
  12.    
  13. }  

LINQ表达式解析

 
 
 
  1. IEnumerable<string> query = from s in names  
  2. where s.Length == 5  
  3. orderby s  
  4. select s.ToUpper(); 

在语义上等同于如下“方法风格(基于方法)的查询”:

 
 
 
  1. IEnumerable<string> query = names 
  2. .Where(s => s.Length == 5)  
  3. .OrderBy(s => s)  
  4. .Select(s => s.ToUpper()); 

LINQ查询表达式解析

 
 
 
  1. Func<string, bool> filter = delegate (string s) {  
  2. return s.Length == 5;};  
  3. Func<string, string> extract = delegate (string s) {  
  4. return s; };  
  5. Func<string, string> project = delegate (string s) {  
  6. return s.ToUpper(); };  
  7. IEnumerable<string> query = names.Where(filter)  
  8. .OrderBy(extract)  
  9. .Select(project); 

查询操作符与扩展方法解析

查询操作符是LINQ中的另外一项重要设施,LINQ使用扩展方法来定义查询操作符,例如where操作符:

 
 
 
  1. namespace System.Linq {  
  2. public static class Enumerable {  
  3. public static IEnumerable<T> Where<T>(  
  4. this IEnumerable<T> source, Func<T, bool> predicate) {  
  5. foreach (T item in source)  
  6. if (predicate(item))  
  7. yield return item;  
  8. }  
  9. }  

【编辑推荐】

  1. LINQ匿名类型分析
  2. LINQ Where子句介绍
  3. LINQ使用Where扩展方法
  4. 介绍LINQ一些强大功能
  5. Linq使用Select浅谈
THE END