LINQ基础(一)

LINQ(Language Integrated Query,语言集成查询),在C#语言中集成了查询语法,可以用相同的语法访问不同的数据源。
  LINQ提供了不同数据源的抽象层,所以可以使用相同的语法。
  这里主要介绍LINQ的核心原理和C#中支持C# LINQ查询的语言扩展。

1.语法
  使用LINQ查询出来自巴西的所以世界冠军。这里可以使用List<T>类的FindAll()方法,但使用LINQ查询语法更简单  

 

 1 static void LINQQuery()
 2         {
 3           //
 4           var query = from r in Formula1.GetChampions()
 5                       where r.Country == "Brazil"
 6                       orderby r.Wins descending
 7                       select r;
 8 
 9           foreach (var r in query)
10           {
11             Console.WriteLine("{0:A}", r);
12           }
13 
14         }
View Code

 

变量query只指定了LINQ查询。该查询不是通过这个赋值语句执行的,而是使用foreach循环访问查询时执行的。

2.扩展方法
  编译器会转换LINQ查询,以调用方法而不是LINQ查询。LINQ为IEnumerable<T>接口提供了各种扩展方法(扩展方法在http://www.cnblogs.com/afei-24/p/6703843.html介绍到),以便用户在实现了该接口的任意集合上使用LINQ查询。
  定义LINQ扩展方法的一个类是System.Linq名称空间中的Enumerable。只需要导入这个名称空间,就打开了这个类的扩展方法的作用域。下面是Where()扩展方法的实现代码:

 

 1 public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source,Func<TSource,bool> predicate)
 2         {
 3             foreach(TSource item in source)
 4             {
 5                 if(predicate(item))
 6                 {
 7                     yield return item;
 8                 }
 9                 
10             }
11         }

 

因为Where()作为一个泛型方法,所以它可以用于包含在集合中的任意类型。实现了IEnumerable<T>接口的任意集合都支持它。

3.推迟查询的执行
  前面提到,在运行期间定义LINQ查询表达式时,查询不会运行。查询在迭代数据项时才会运行。
  举个例子:  

 

 1 static void DeferredQuery()
 2         {
 3           var names = new List<string> { "Nino", "Alberto", "Juan", "Mike", "Phil" };
 4 
 5           var namesWithJ = from n in names
 6                            where n.StartsWith("J")
 7                            orderby n
 8                            select n;
 9 
10           Console.WriteLine("First iteration");
11           foreach (string name in namesWithJ)
12           {
13             Console.WriteLine(name);
14           }
15           Console.WriteLine();
16 
17           names.Add("John");
18           names.Add("Jim");
19           names.Add("Jack");
20           names.Add("Denny");
21 
22           Console.WriteLine("Second iteration");
23           foreach (string name in namesWithJ)
24           {
25             Console.WriteLine(name);
26           }
27 
28         }
View Code

 

  输出:
  
  因为查询在迭代时才执行,所以在第一次输出后有添加项再输出,会显示又添加的项。

  但在调用方法ToArray(),ToList等方法时,不会延迟执行:  

 

 1 static void NotDeferredQuery()
 2         {
 3             var names = new List<string> { "Nino", "Alberto", "Juan", "Mike", "Phil" };
 4 
 5             var namesWithJ = (from n in names
 6                              where n.StartsWith("J")
 7                              orderby n
 8                              select n).ToList();
 9 
10             Console.WriteLine("First iteration");
11             foreach (string name in namesWithJ)
12             {
13                 Console.WriteLine(name);
14             }
15             Console.WriteLine();
16 
17             names.Add("John");
18             names.Add("Jim");
19             names.Add("Jack");
20             names.Add("Denny");
21 
22             Console.WriteLine("Second iteration");
23             foreach (string name in namesWithJ)
24             {
25                 Console.WriteLine(name);
26             }
27 
28         }
View Code

 

输出:
  




下面是用到的类,后续的也需要用到这些代码。

 

  1 //这个类创建需要的列表
  2         public static class Formula1
  3           {
  4             private static List<Racer> racers;
  5             //返回一组赛车手
  6             public static IList<Racer> GetChampions()
  7             {
  8               if (racers == null)
  9               {
 10                 racers = new List<Racer>(40);
 11                 racers.Add(new Racer("Nino", "Farina", "Italy", 33, 5,
 12            new int[] { 1950 }, new string[] { "Alfa Romeo" }));
 13                 racers.Add(new Racer("Alberto", "Ascari", "Italy", 32, 10, 
 14           new int[] { 1952, 1953 }, new string[] { "Ferrari" }));
 15                 racers.Add(new Racer("Juan Manuel", "Fangio", "Argentina", 51, 24,
 16            new int[] { 1951, 1954, 1955, 1956, 1957 }, new string[] { "Alfa Romeo", "Maserati", "Mercedes", "Ferrari" }));
 17                 racers.Add(new Racer("Mike", "Hawthorn", "UK", 45, 3,
 18            new int[] { 1958 }, new string[] { "Ferrari" }));
 19                 racers.Add(new Racer("Phil", "Hill", "USA", 48, 3,
 20            new int[] { 1961 }, new string[] { "Ferrari" }));
 21                 racers.Add(new Racer("John", "Surtees", "UK", 111, 6,
 22            new int[] { 1964 }, new string[] { "Ferrari" }));
 23                 racers.Add(new Racer("Jim", "Clark", "UK", 72, 25, 
 24           new int[] { 1963, 1965 }, new string[] { "Lotus" }));
 25                 racers.Add(new Racer("Jack", "Brabham", "Australia", 125, 14,
 26            new int[] { 1959, 1960, 1966 }, new string[] { "Cooper", "Brabham" }));
 27                 racers.Add(new Racer("Denny", "Hulme", "New Zealand", 112, 8, 
 28           new int[] { 1967 }, new string[] { "Brabham" }));
 29               }
 30 
 31               return racers;
 32             }
 33 
 34 
 35             private static List<Team> teams;
 36             //返回一组冠军车队
 37             public static IList<Team> GetContructorChampions()
 38             {
 39               if (teams == null)
 40               {
 41                 teams = new List<Team>()
 42                         {
 43                             new Team("Vanwall", 1958),
 44                             new Team("Cooper", 1959, 1960),
 45                             new Team("Ferrari", 1961, 1964, 1975, 1976, 1977, 1979, 1982, 1983, 1999, 
 46                     2000, 2001, 2002, 2003, 2004, 2007, 2008),
 47                             new Team("BRM", 1962),
 48                             new Team("Lotus", 1963, 1965, 1968, 1970, 1972, 1973, 1978),
 49                             new Team("Brabham", 1966, 1967),
 50                             new Team("Matra", 1969),
 51                             new Team("Tyrrell", 1971),
 52                             new Team("McLaren", 1974, 1984, 1985, 1988, 1989, 1990, 1991, 1998),
 53                             new Team("Williams", 1980, 1981, 1986, 1987, 1992, 1993, 1994, 1996, 1997),
 54                             new Team("Benetton", 1995),
 55                             new Team("Renault", 2005, 2006 ),
 56                             new Team("Brawn GP", 2009),
 57                             new Team("Red Bull Racing", 2010, 2011)
 58                         };
 59               }
 60               return teams;
 61             }
 62 
 63             private static List<Championship> championships;
 64             //返回GetChampionships类型的集合
 65             public static IEnumerable<Championship> GetChampionships()
 66             {
 67               if (championships == null)
 68               {
 69                 championships = new List<Championship>();
 70                 championships.Add(new Championship
 71                 {
 72                   Year = 1950,
 73                   First = "Nino Farina",
 74                   Second = "Juan Manuel Fangio",
 75                   Third = "Luigi Fagioli"
 76                 });
 77                 championships.Add(new Championship
 78                 {
 79                   Year = 1951,
 80                   First = "Juan Manuel Fangio",
 81                   Second = "Alberto Ascari",
 82                   Third = "Froilan Gonzalez"
 83                 });
 84                 championships.Add(new Championship
 85                 {
 86                   Year = 1952,
 87                   First = "Alberto Ascari",
 88                   Second = "Nino Farina",
 89                   Third = "Piero Taruffi"
 90                 });
 91                 championships.Add(new Championship
 92                 {
 93                   Year = 1953,
 94                   First = "Alberto Ascari",
 95                   Second = "Juan Manuel Fangio",
 96                   Third = "Nino Farina"
 97                 });
 98                 championships.Add(new Championship
 99                 {
100                   Year = 1954,
101                   First = "Juan Manuel Fangio",
102                   Second = "Froilan Gonzalez",
103                   Third = "Mike Hawthorn"
104                 });
105                 championships.Add(new Championship
106                 {
107                   Year = 1955,
108                   First = "Juan Manuel Fangio",
109                   Second = "Stirling Moss",
110                   Third = "Eugenio Castellotti"
111                 });
112                 championships.Add(new Championship
113                 {
114                   Year = 1956,
115                   First = "Juan Manuel Fangio",
116                   Second = "Stirling Moss",
117                   Third = "Peter Collins"
118                 });
119                 
120                 
121               }
122               return championships;
123             }
124         }
View Code

 

 1 //车手类
 2     
 3     [Serializable]
 4       public class Racer : IComparable<Racer>, IFormattable
 5       {
 6         public Racer(string firstName, string lastName, string country, int starts, int wins)
 7           : this(firstName, lastName, country, starts, wins, null, null)
 8         {
 9         }
10         public Racer(string firstName, string lastName, string country, int starts,
11        int wins, IEnumerable<int> years, IEnumerable<string> cars)
12         {
13           this.FirstName = firstName;
14           this.LastName = lastName;
15           this.Country = country;
16           this.Starts = starts;
17           this.Wins = wins;
18           this.Years = new List<int>(years);
19           this.Cars = new List<string>(cars);
20         }
21         //单值属性
22         public string FirstName { get; set; }
23         public string LastName { get; set; }
24         public string Country { get; set; }
25         public int Wins { get; set; }
26         public int Starts { get; set; }
27         //多值属性,车手可能多次获得冠军,所在的车队也可能不同
28         public IEnumerable<string> Cars { get; private set; }
29         public IEnumerable<int> Years { get; private set; }
30 
31         public override string ToString()
32         {
33           return String.Format("{0} {1}", FirstName, LastName);
34         }
35 
36         public int CompareTo(Racer other)
37         {
38           if (other == null) return -1;
39           return string.Compare(this.LastName, other.LastName);
40         }
41 
42         public string ToString(string format)
43         {
44           return ToString(format, null);
45         }
46 
47         public string ToString(string format,
48               IFormatProvider formatProvider)
49         {
50           switch (format)
51           {
52             case null:
53             case "N":
54               return ToString();
55             case "F":
56               return FirstName;
57             case "L":
58               return LastName;
59             case "C":
60               return Country;
61             case "S":
62               return Starts.ToString();
63             case "W":
64               return Wins.ToString();
65             case "A":
66               return String.Format("{0} {1}, {2}; starts: {3}, wins: {4}",
67                     FirstName, LastName, Country, Starts, Wins);
68             default:
69               throw new FormatException(String.Format("Format {0} not supported", format));
70           }
71         }
72       }
View Code
 1 //获得冠军的车队
 2         [Serializable]
 3         public class Team
 4         {
 5             public Team(string name, params int[] years)
 6             {
 7                 this.Name = name;
 8                 this.Years = new List<int>(years);
 9             }
10             public string Name { get; private set; }
11             public IEnumerable<int> Years { get; private set; }
12         }
13         
14         
15         //获奖选手和年份
16           public class Championship
17           {
18             public int Year { get; set; }
19             public string First { get; set; }
20             public string Second { get; set; }
21             public string Third { get; set; }
22           }
View Code

 

 

 

 

 

[转载 http://www.cnblogs.com/afei-24/p/6841361.html]

posted @ 2017-05-17 11:30  ★·°勿忘初心  阅读(218)  评论(0编辑  收藏  举报