C# LINQ标准查询操作符

首先添加数据集合

 1 [Serializable]
 2     public class Racer : IComparable<Racer>, IFormattable
 3     {
 4         public Racer()
 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, int wins, IEnumerable<int> years, IEnumerable<string> cars)
11         {
12             this.FirstName = firstName;
13             this.LastName = lastName;
14             this.Country = country;
15             this.Starts = starts;
16             this.Wins = wins;
17             this.Years = new List<int>(years);
18             this.Cars = new List<string>(cars);
19         }
20         public string FirstName { get; set; }
21         public string LastName { get; set; }
22         public string Country { get; set; }
23         public int Wins { get; set; }
24         public int Starts { get; set; }
25         public IEnumerable<string> Cars { get; private set; }
26         public IEnumerable<int> Years { get; private set; }
27
28         public override string ToString()
29         {
30             return String.Format("{0} {1}", FirstName, LastName);
31         }
32
33         public int CompareTo(Racer other)
34         {
35             if (other == null) return -1;
36             return string.Compare(this.LastName, other.LastName);
37         }
38
39         public string ToString(string format)
40         {
41             return ToString(format, null);
42         }
43
44         public string ToString(string format,
45               IFormatProvider formatProvider)
46         {
47             switch (format)
48             {
49                 case null:
50                 case "N":
51                     return ToString();
52                 case "F":
53                     return FirstName;
54                 case "L":
55                     return LastName;
56                 case "C":
57                     return Country;
58                 case "S":
59                     return Starts.ToString();
60                 case "W":
61                     return Wins.ToString();
62                 case "A":
63                     return String.Format("{0} {1}, {2}; starts: {3}, wins: {4}",
64                           FirstName, LastName, Country, Starts, Wins);
65                 default:
66                     throw new FormatException(String.Format("Format {0} not supported", format));
67             }
68         }
69     }

 1  private static List<Racer> racers;
 2
 3     public static IList<Racer> GetChampions()
 4     {
 5       if (racers == null)
 6       {
 7         racers = new List<Racer>(40);
 8         racers.Add(new Racer("Nino", "Farina", "Italy", 33, 5, new int[] { 1950 }, new string[] { "Alfa Romeo" }));
 9         racers.Add(new Racer("Alberto", "Ascari", "Italy", 32, 10, new int[] { 1952, 1953 }, new string[] { "Ferrari" }));
10         racers.Add(new Racer("Juan Manuel", "Fangio", "Argentina", 51, 24, new int[] { 1951, 1954, 1955, 1956, 1957 }, new string[] { "Alfa Romeo", "Maserati", "Mercedes", "Ferrari" }));
11         racers.Add(new Racer("Mike", "Hawthorn", "UK", 45, 3, new int[] { 1958 }, new string[] { "Ferrari" }));
12         racers.Add(new Racer("Phil", "Hill", "USA", 48, 3, new int[] { 1961 }, new string[] { "Ferrari" }));
13         racers.Add(new Racer("John", "Surtees", "UK", 111, 6, new int[] { 1964 }, new string[] { "Ferrari" }));
14         racers.Add(new Racer("Jim", "Clark", "UK", 72, 25, new int[] { 1963, 1965 }, new string[] { "Lotus" }));
15         racers.Add(new Racer("Jack", "Brabham", "Australia", 125, 14, new int[] { 1959, 1960, 1966 }, new string[] { "Cooper", "Brabham" }));
16         racers.Add(new Racer("Denny", "Hulme", "New Zealand", 112, 8, new int[] { 1967 }, new string[] { "Brabham" }));
17         racers.Add(new Racer("Graham", "Hill", "UK", 176, 14, new int[] { 1962, 1968 }, new string[] { "BRM", "Lotus" }));
18         racers.Add(new Racer("Jochen", "Rindt", "Austria", 60, 6, new int[] { 1970 }, new string[] { "Lotus" }));
19         racers.Add(new Racer("Jackie", "Stewart", "UK", 99, 27, new int[] { 1969, 1971, 1973 }, new string[] { "Matra", "Tyrrell" }));
20         racers.Add(new Racer("Emerson", "Fittipaldi", "Brazil", 143, 14, new int[] { 1972, 1974 }, new string[] { "Lotus", "McLaren" }));
21         racers.Add(new Racer("James", "Hunt", "UK", 91, 10, new int[] { 1976 }, new string[] { "McLaren" }));
22         racers.Add(new Racer("Mario", "Andretti", "USA", 128, 12, new int[] { 1978 }, new string[] { "Lotus" }));
23         racers.Add(new Racer("Jody", "Scheckter", "South Africa", 112, 10, new int[] { 1979 }, new string[] { "Ferrari" }));
24         racers.Add(new Racer("Alan", "Jones", "Australia", 115, 12, new int[] { 1980 }, new string[] { "Williams" }));
25         racers.Add(new Racer("Keke", "Rosberg", "Finland", 114, 5, new int[] { 1982 }, new string[] { "Williams" }));
26         racers.Add(new Racer("Niki", "Lauda", "Austria", 173, 25, new int[] { 1975, 1977, 1984 }, new string[] { "Ferrari", "McLaren" }));
27         racers.Add(new Racer("Nelson", "Piquet", "Brazil", 204, 23, new int[] { 1981, 1983, 1987 }, new string[] { "Brabham", "Williams" }));
28         racers.Add(new Racer("Ayrton", "Senna", "Brazil", 161, 41, new int[] { 1988, 1990, 1991 }, new string[] { "McLaren" }));
29         racers.Add(new Racer("Nigel", "Mansell", "UK", 187, 31, new int[] { 1992 }, new string[] { "Williams" }));
30         racers.Add(new Racer("Alain", "Prost", "France", 197, 51, new int[] { 1985, 1986, 1989, 1993 }, new string[] { "McLaren", "Williams" }));
31         racers.Add(new Racer("Damon", "Hill", "UK", 114, 22, new int[] { 1996 }, new string[] { "Williams" }));
32         racers.Add(new Racer("Jacques", "Villeneuve", "Canada", 165, 11, new int[] { 1997 }, new string[] { "Williams" }));
33         racers.Add(new Racer("Mika", "Hakkinen", "Finland", 160, 20, new int[] { 1998, 1999 }, new string[] { "McLaren" }));
34         racers.Add(new Racer("Michael", "Schumacher", "Germany", 287, 91, new int[] { 1994, 1995, 2000, 2001, 2002, 2003, 2004 }, new string[] { "Benetton", "Ferrari" }));
35         racers.Add(new Racer("Fernando", "Alonso", "Spain", 177, 27, new int[] { 2005, 2006 }, new string[] { "Renault" }));
36         racers.Add(new Racer("Kimi", "R?ikk?nen", "Finland", 148, 17, new int[] { 2007 }, new string[] { "Ferrari" }));
37         racers.Add(new Racer("Lewis", "Hamilton", "UK", 90, 17, new int[] { 2008 }, new string[] { "McLaren" }));
38         racers.Add(new Racer("Jenson", "Button", "UK", 208, 12, new int[] { 2009 }, new string[] { "Brawn GP" }));
39         racers.Add(new Racer("Sebastian", "Vettel", "Germany", 81, 21, new int[] { 2010, 2011 }, new string[] { "Red Bull Racing" }));
40       }
41
42       return racers;
43     }

1、where子句

1 var racers = from r in Formula1.GetChampions()
2                          where r.Wins > 15 && (r.Country == "Brazil" || r.Country == "Austria")
3                          select r;
4 var item = Formula1.GetChampions().Where(p => p.Wins > 15 && (p.Country == "Brazil" || p.Country == "Austria")).Select(r => r);

2、根据索引筛选

1     var racers = Formula1.GetChampions().
2                     Where((r, index) => r.LastName.StartsWith("A") && index % 2 != 0);

3、类型筛选

1  object[] data = { "one", 2, 3, "four", "five", 6 };
2  var query = data.OfType<string>();

4、复合的from子句

1          var ferrariDrivers = from r in Formula1.GetChampions()
2                                  from c in r.Cars
3                                  where c == "Ferrari"
4                                  orderby r.LastName
5                                  select r.FirstName + " " + r.LastName;
6             var item = Formula1.GetChampions().SelectMany(r => r.Cars, (r, c) => new { Racer = r, Car = c }).
7                      Where(r => r.Car == "Ferrari").OrderBy(r => r.Racer.LastName).Select(r => r.Racer.FirstName + "" + r.Racer.LastName);

5、排序

1 var racers = from r in Formula1.GetChampions()
2                          where r.Country == "Brazil"
3                          orderby r.Wins descending
4                          select r;
5 var racers2= from r in Formula1.GetChampions()
6                          orderby r.Country,r.LastName,r.FirstName
7                          select r;
8 var racers3 = Formula1.GetChampions().OrderBy(r => r.Country).ThenBy(r => r.LastName).ThenBy(r => r.FirstName);

6、分组

 1
 2 var countries = from r in Formula1.GetChampions()
 3                             group r by r.Country into g
 4                             orderby g.Count() descending, g.Key
 5                             where g.Count() >= 2
 6                             select new { Country = g.Key, Count = g.Count() };
 7
 8 var item = Formula1.GetChampions().GroupBy(r => r.Country).OrderByDescending(p => p.Count()).
 9                     ThenBy(p => p.Key).Where(p => p.Count() >= 2).Select(p => new { Country = p.Key, Count = p.Count() });
10         

7、内链接

 1   var racers = from r in Formula1.GetChampions()
 2                          from y in r.Years
 3                          select new
 4                          {
 5                              Year = y,
 6                              Name = r.FirstName + " " + r.LastName
 7                          };
 8
 9             var teams = from t in Formula1.GetContructorChampions()
10                         from y in t.Years
11                         select new
12                         {
13                             Year = y,
14                             Name = t.Name
15                         };

8、左连接

 1  var racersAndTeams =
 2               (from r in racers
 3                join t in teams on r.Year equals t.Year into rt
 4                from t in rt.DefaultIfEmpty()
 5                orderby r.Year
 6                select new
 7                {
 8                    Year = r.Year,
 9                    Champion = r.Name,
10                    Constructor = t == null ? "no constructor championship" : t.Name
11                }).Take(10);

9、zip 合并

 1  var racerNames = from r in Formula1.GetChampions()
 2                              where r.Country == "Italy"
 3                              orderby r.Wins descending
 4                              select new
 5                              {
 6                                  Name = r.FirstName + " " + r.LastName
 7                              };
 8
 9             var racerNamesAndStarts = from r in Formula1.GetChampions()
10                                       where r.Country == "Italy"
11                                       orderby r.Wins descending
12                                       select new
13                                       {
14                                           LastName = r.LastName,
15                                           Starts = r.Starts
16                                       };
17
18
19             var racers = racerNames.Zip(racerNamesAndStarts, (first, second) => first.Name + ", starts: " + second.Starts);

10、聚合函数

 1  var query = from r in Formula1.GetChampions()
 2                         let numberYears = r.Years.Count()
 3
 4                         where numberYears >= 3
 5                         orderby numberYears descending, r.LastName
 6                         select new
 7                         {
 8                             Name = r.FirstName + " " + r.LastName,
 9                             TimesChampion = numberYears
10                         };
11
12  var countries = (from c in
13                                  from r in Formula1.GetChampions()
14                                  group r by r.Country into c
15                                  select new
16                                  {
17                                      Country = c.Key,
18                                      Wins = (from r1 in c
19                                              select r1.Wins).Sum()
20                                  }
21                              orderby c.Wins descending, c.Country
22                              select c).Take(5);
时间: 2024-08-06 14:07:10

C# LINQ标准查询操作符的相关文章

Linq 标准查询操作符三

本文介绍了LINQ标准查询操作符.没有这些操作符,LINQ就不会存在.本文为理解这些操作符的功能提供了很好的基础.了解它们将会很有帮助,因为LINQ的各种Provider都是基于这些操作符来完成各自丰富的功能. 一.投影操作符 1. Select Select操作符对单个序列或集合中的值进行投影.下面的示例中使用select从序列中返回Employee表的所有列: using (NorthwindDataContext db = new NorthwindDataContext()) { //查

LINQ标准查询操作符详解(转)

 一. 关于LINQ       LINQ 英文全称是“Language-Integrated Query”,中文为“语言集成查询”,它是微软首席架构师.Delphi 之父和C# 之父——Anders Hejlsberg 提出的并由其团队着力打造的一组用于c#和Visual Basic语言的扩展,为 C# 和 Visual Basic 语言语法提供强大的查询功能.微软从2003年开始启动LINQ的开发,在VisualStudio2008中开始加入LINQ功能. LINQ提供的便利: 1)使用一种

LINQ标准查询操作符(三)——Aggregate、Average、Distinct、Except、Intersect、Union、Empty、DefaultIfEmpty、Range、Repeat

本文来自:http://blog.csdn.net/xuejianwu/article/details/6931903 七.聚合操作符 聚合函数将在序列上执行特定的计算,并返回单个值,如计算给定序列平均值.最大值等.共有7种LINQ聚合查询操作符:Aggregate.Average.Count.LongCount.Max.Min和Sum. 1. Aggregate Aggregate操作符对集合值执行自定义聚合运算.例如,需要列出所有产品类别清单,每个类别名称之间用顿号连接.以下的代码演示了这一

LINQ标准查询操作符(四)—AsEnumerable,Cast,OfType,ToArray,ToDictionary,ToList,ToLookup,First,Last,ElementAt

本文来自:http://blog.csdn.net/xuejianwu/article/details/6931926 十.转换操作符 转换操作符是用来实现将输入对象的类型转变为序列的功能.名称以“As”开头的转换方法可更改源集合的静态类型但不枚举(延迟加载)此源集合.名称以“To”开头的方法可枚举(即时加载)源集合并将项放入相应的集合类型. 1. AsEnumerable 所有实现了IEnumerable<T>接口的类型都可以调用此方法来获取一个IEnumerable<T>集合.

LINQ标准查询操作符(一)——select、SelectMany、Where、OrderBy、OrderByDescending、ThenBy、ThenByDescending和Reverse

本文来自:http://blog.csdn.net/xuejianwu/article/details/6931804 一.投影操作符 1. Select Select操作符对单个序列或集合中的值进行投影.下面的示例中使用select从序列中返回Employee表的所有列: [csharp] view plaincopy using (NorthwindDataContext db=new NorthwindDataContext()) { //查询语法 var query = from e i

LINQ标准查询操作符(二)——Join、GroupJoin、GroupBy、Concat、

本文来自:http://blog.csdn.net/xuejianwu/article/details/6931853 四.联接操作符 联接是指将一个数据源对象与另一个数据源对象进行关联或者联合的操作.这两个数据源对象通过一个共同的值或者属性进行关联. LINQ有两个联接操作符:Join和GroupJoin. 1. Join Join操作符类似于T-SQL中的inner join,它将两个数据源相联接,根据两个数据源中相等的值进行匹配.例如,可以将产品表与产品类别表相联接,得到产品名称和与其相对

Linq to OBJECT延时标准查询操作符

1.Where 操作符用于限定输入集合中的元素,将符合条件的元素组织声称一个序列结果. 2.Select  操作符用于根据输入序列中的元素创建相应的输出序列中的元素,输出序列中的元素类型可以与输入序列中的元素类型相同,也可以不同.下面来看看Select方法的原型. 3.SelectMany 操作符用于根据输入序列中的每一个元素,在输出序列中创建相应的零个或者多个元素,与Select操作符不同,Select操作符会根据输入序列中的每一个元素创建一个对应的输出序列元素,而SelectMany操作符可

Linq to BBJECT之非延时标准查询操作符

非延时标准查询操作符是指不具备延时查询特性的标准查询操作符,这些操作符一般用于辅助延时标准查询操作符使用. 1.ToArray操作符 ToArray操作符用于将一个输入序列转换成一个数组. 方法原型: public static TSource[] ToArray<TSource>(this IEnumerable<TSource> source); 代码示例: static void Main(string[] args) { List<int> listInt =

Linq to Object之非延迟标准查询操作符

非延时标准查询操作符是指不具备延时查询特性的标准查询操作符,这些操作符一般用于辅助延时标准查询操作符使用. 1.ToArray操作符 ToArray操作符用于将一个输入序列转换成一个数组. 方法原型: public static TSource[] ToArray<TSource>(this IEnumerable<TSource> source); 代码示例: static void Main(string[] args) { List<int> listInt =