Linq101-Quantifiers

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 
 5 namespace Linq101
 6 {
 7     class Quantifiers
 8     {
 9         /// <summary>
10         /// This sample uses Any to determine if any of the words in the array contain the substring 'ei'.
11         /// </summary>
12         public void Linq67()
13         {
14             string[] words = { "believe", "relief", "receipt", "field" };
15 
16             bool iAfterE = words.Any(w => w.Contains("ei"));
17 
18             Console.WriteLine("There is a word that contains in the list that contains 'ei': {0}", iAfterE);
19         }
20 
21         /// <summary>
22         /// This sample uses Any to return a grouped a list of products only for categories that have at least one product that is out of stock.
23         /// </summary>
24         public void Linq68()
25         {
26             List<Data.Product> products = Data.GetProductList();
27             var productGroups = from p in products
28                                 group p by p.Category
29                                     into g
30                                     where g.Any(p => p.UnitsInStock == 0)
31                                     select new { Category = g.Key, Products = g };
32 
33             ObjectDumper.Write(productGroups, 1);
34         }
35 
36         /// <summary>
37         /// This sample uses All to determine whether an array contains only odd numbers.
38         /// </summary>
39         public void Linq69()
40         {
41             int[] numbers = { 1, 11, 3, 19, 41, 65, 19 };
42 
43             bool onlyOdd = numbers.All(n => n % 2 == 1);
44 
45             Console.WriteLine("The list contains only odd numbers : {0}", onlyOdd);
46         }
47 
48         /// <summary>
49         /// This sample uses All to return a grouped a list of products only for categories that have all of their products in stock.
50         /// </summary>
51         public void Linq70()
52         {
53             List<Data.Product> products = Data.GetProductList();
54 
55             var productGroups = from p in products
56                                 group p by p.Category
57                                     into g
58                                     where g.All(p => p.UnitsInStock > 0)
59                                     select new { Category = g.Key, products = g };
60 
61             ObjectDumper.Write(productGroups, 1);
62         }
63     }
64 }

 

posted @ 2015-03-12 15:31  David Huang  阅读(300)  评论(0编辑  收藏  举报