LINQ基础(一)

  一、学习LINQ需要先了解以下知识点:

        1.1 委托

        1.2 匿名方法

        1.3 Lambda表达式

        1.4 扩展方法

  二、LINQ原理:

         

    from s in names where s.length == 5

             orderby s 

             select  s.ToUpper();

           上面这句编译器最终会被转化为下面这句去执行:

           names.Where(s=>s.Length == 5)

                    .OrderBy(s=>s)

         .Select(s=>s.ToUpper());   

    

     

    

     示例:

      

 1 public class Program
 2     {
 3         
 4         static void Main(string[] args)
 5         {
 6             string[] Names = { "Bruke", "Connor", "Frank", "Everett", "Albert", "George", "Harris", "David" };
 7 
 8             //第一种
 9             IEnumerable<string> query = from s in Names
10                                         where s.Length == 5
11                                         orderby s
12                                         select s.ToUpper();
13 
14             //第二种
15             IEnumerable<string> query1 = Names.Where(s => s.Length == 5)
16                                              .OrderBy(s => s)
17                                              .Select(s => s.ToUpper());
18 
19             //第三种
20             IEnumerable<string> query2 = Enumerable.Where(Names,s => s.Length == 5)
21                                  .OrderBy(s => s)
22                                  .Select(s => s.ToUpper());
23 
24             //以上三种写法都是正确的,只不过Names.Where 这种调用方式,返回的是Enumberable类型,在这个类型底层,还是Enumberable 写了一个扩展方法,所有可以使用
25             //第二种方式调用,写全了,应该是第三种方式进行调用,因为Enumberable泛型定义了扩展方法,所有可以这样使用 Enumerable.Where
26 
27 
28             foreach (string item in query)
29             {
30                 Console.WriteLine(item);
31             }
32             Console.ReadKey();        
33         }
34     }

    Webcast视频:C# 3.0 锐利体验系列课程(3):查询表达式LINQ(1)

原文地址:https://www.cnblogs.com/luyuwei/p/3653086.html