101个linq例子

FirstOrDefault - Simple

public void Linq61() 
  
{ 
    int[] numbers = { }; 
  
    int firstNumOrDefault = numbers.FirstOrDefault(); 
  
    Console.WriteLine(firstNumOrDefault); 
}

Result

0

FirstOrDefault - Condition

public void Linq62() 
{ 
    List<Product> products = GetProductList(); 
  
    Product product789 = products.FirstOrDefault(p => p.ProductID == 789); 
 
    Console.WriteLine("Product 789 exists: {0}", product789 != null); 
}

Result

Product 789 exists: False

ElementAt

public void Linq64() 
{ 
    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 
  
    int fourthLowNum = ( 
        from n in numbers 
        where n > 5 
        select n) 
        .ElementAt(1);  // 第二个数字的索引是 1,因为序列使用基于 0 的索引
 
    Console.WriteLine("Second number > 5: {0}", fourthLowNum); 
}
Result

Second number > 5: 8

Any - Simple

此示例使用 Any 确定是否任何单词数组中包含的子字符串 ei。

public void Linq67() 
{ 
    string[] words = { "believe", "relief", "receipt", "field" }; 
  
    bool iAfterE = words.Any(w => w.Contains("ei")); 
 
    Console.WriteLine("There is a word that contains in the list that contains 'ei': {0}", iAfterE); 
}

Result

There is a word that contains in the list that contains 'ei': True

Any - Grouped

此示例使用 Any 返回分组的产品仅供有缺货的至少一个产品的类别列表。

public void Linq69() 
{ 
    List<Product> products = GetProductList(); 
    var productGroups = 
        from p in products 
        group p by p.Category into g 
        where g.Any(p => p.UnitsInStock == 0) 
        select new { Category = g.Key, Products = g }; 
 
    ObjectDumper.Write(productGroups, 1);  
}

Result

Category=Condiments    Products=... 
  Products: ProductID=3  ProductName=Aniseed Syrup      Category=Condiments    UnitPrice=10.0000      UnitsInStock=13 
  Products: ProductID=4  ProductName=Chef Anton's Cajun Seasoning        Category=Condiments    UnitPrice=22.0000      UnitsInStock=53 
  Products: ProductID=5  ProductName=Chef Anton's Gumbo Mix      Category=Condiments    UnitPrice=21.3500      UnitsInStock=0 
  Products: ProductID=6  ProductName=Grandma's Boysenberry Spread        Category=Condiments    UnitPrice=25.0000      UnitsInStock=120 
  Products: ProductID=8  ProductName=Northwoods Cranberry Sauce  Category=Condiments    UnitPrice=40.0000      UnitsInStock=6 
  Products: ProductID=15  ProductName=Genen Shouyu        Category=Condiments    UnitPrice=15.5000      UnitsInStock=39 
  Products: ProductID=44  ProductName=Gula Malacca        Category=Condiments    UnitPrice=19.4500      UnitsInStock=27 
  Products: ProductID=61  ProductName=Sirop d'érable      Category=Condiments    UnitPrice=28.5000      UnitsInStock=113 
  Products: ProductID=63  ProductName=Vegie-spread        Category=Condiments    UnitPrice=43.9000      UnitsInStock=24 
  Products: ProductID=65  ProductName=Louisiana Fiery Hot Pepper Sauce    Category=Condiments    UnitPrice=21.0500      UnitsInStock=76 
  Products: ProductID=66  ProductName=Louisiana Hot Spiced Okra  Category=Condiments    UnitPrice=17.0000      UnitsInStock=4 
  Products: ProductID=77  ProductName=Original Frankfurter grüne Soße    Category=Condiments    UnitPrice=13.0000      UnitsInStock=32 
Category=Meat/Poultry  Products=... 
  Products: ProductID=9  ProductName=Mishi Kobe Niku    Category=Meat/Poultry  UnitPrice=97.0000      UnitsInStock=29 
  Products: ProductID=17  ProductName=Alice Mutton        Category=Meat/Poultry  UnitPrice=39.0000      UnitsInStock=0 
  Products: ProductID=29  ProductName=Thüringer Rostbratwurst    Category=Meat/Poultry  UnitPrice=123.7900      UnitsInStock=0 
  Products: ProductID=53  ProductName=Perth Pasties      Category=Meat/Poultry  UnitPrice=32.8000      UnitsInStock=0 
  Products: ProductID=54  ProductName=Tourtière  Category=Meat/Poultry  UnitPrice=7.4500        UnitsInStock=21 
  Products: ProductID=55  ProductName=Pâté chinois        Category=Meat/Poultry  UnitPrice=24.0000      UnitsInStock=115 
Category=Dairy Products        Products=... 
  Products: ProductID=11  ProductName=Queso Cabrales      Category=Dairy Products        UnitPrice=21.0000      UnitsInStock=22 
  Products: ProductID=12  ProductName=Queso Manchego La Pastora  Category=Dairy Products        UnitPrice=38.0000      UnitsInStock=86 
  Products: ProductID=31  ProductName=Gorgonzola Telino  Category=Dairy Products        UnitPrice=12.5000      UnitsInStock=0 
  Products: ProductID=32  ProductName=Mascarpone Fabioli  Category=Dairy Products        UnitPrice=32.0000      UnitsInStock=9 
  Products: ProductID=33  ProductName=Geitost    Category=Dairy Products        UnitPrice=2.5000        UnitsInStock=112 
  Products: ProductID=59  ProductName=Raclette Courdavault        Category=Dairy Products        UnitPrice=55.0000      UnitsInStock=79 
  Products: ProductID=60  ProductName=Camembert Pierrot  Category=Dairy Products        UnitPrice=34.0000      UnitsInStock=19 
  Products: ProductID=69  ProductName=Gudbrandsdalsost    Category=Dairy Products        UnitPrice=36.0000      UnitsInStock=26 
  Products: ProductID=71  ProductName=Flotemysost        Category=Dairy Products        UnitPrice=21.5000      UnitsInStock=26 
  Products: ProductID=72  ProductName=Mozzarella di Giovanni      Category=Dairy Products        UnitPrice=34.8000      UnitsInStock=14

All - Simple

此示例使用 All 来确定数组是否包含偶数。

public void Linq70() 
{  
    int[] numbers = { 1, 11, 3, 19, 41, 65, 19 }; 
  
    bool onlyOdd = numbers.All(n => n % 2 == 1); 
  
    Console.WriteLine("The list contains only odd numbers: {0}", onlyOdd); 
}
Result

 

The list contains only odd numbers: True

All - Grouped

public void Linq72() 
{ 
    List<Product> products = GetProductList(); 
  
    var productGroups = 
        from p in products 
        group p by p.Category into g 
        where g.All(p => p.UnitsInStock > 0) 
        select new { Category = g.Key, Products = g }; 
     
    ObjectDumper.Write(productGroups, 1); 
}

Result

Category=Beverages      Products=... 
  Products: ProductID=1  ProductName=Chai        Category=Beverages      UnitPrice=18.0000      UnitsInStock=39 
  Products: ProductID=2  ProductName=Chang      Category=Beverages      UnitPrice=19.0000      UnitsInStock=17 
  Products: ProductID=24  ProductName=Guaraná Fantástica  Category=Beverages      UnitPrice=4.5000        UnitsInStock=20 
  Products: ProductID=34  ProductName=Sasquatch Ale      Category=Beverages      UnitPrice=14.0000      UnitsInStock=111 
  Products: ProductID=35  ProductName=Steeleye Stout      Category=Beverages      UnitPrice=18.0000      UnitsInStock=20 
  Products: ProductID=38  ProductName=Côte de Blaye      Category=Beverages      UnitPrice=263.5000      UnitsInStock=17 
  Products: ProductID=39  ProductName=Chartreuse verte    Category=Beverages      UnitPrice=18.0000      UnitsInStock=69 
  Products: ProductID=43  ProductName=Ipoh Coffee        Category=Beverages      UnitPrice=46.0000      UnitsInStock=17 
  Products: ProductID=67  ProductName=Laughing Lumberjack Lager  Category=Beverages      UnitPrice=14.0000      UnitsInStock=52 
  Products: ProductID=70  ProductName=Outback Lager      Category=Beverages      UnitPrice=15.0000      UnitsInStock=15 
  Products: ProductID=75  ProductName=Rhönbräu Klosterbier        Category=Beverages      UnitPrice=7.7500        UnitsInStock=125 
  Products: ProductID=76  ProductName=Lakkalikööri        Category=Beverages      UnitPrice=18.0000      UnitsInStock=57 

Count - Simple  

获取列表中没有重复的元素数量

public void Linq73() 
{ 
    int[] factorsOf300 = { 2, 2, 3, 5, 5 }; 
  
    int uniqueFactors = factorsOf300.Distinct().Count(); 
  
    Console.WriteLine("There are {0} unique factorsof300.", uniqueFactors); 
}
Result

There are 3 unique factorsof300.

Count - Nested

public void Linq76() 
{ 
    List<Customer> customers = GetCustomerList(); 
  
    var orderCounts = 
        from c in customers 
        select new { c.CustomerID, OrderCount = c.Orders.Count() }; 
  
    ObjectDumper.Write(orderCounts); 
}

 

Result
CustomerID=ALFKI OrderCount=6
CustomerID=ANATR OrderCount=4
CustomerID=ANTON OrderCount=7
CustomerID=AROUT OrderCount=13
CustomerID=BERGS OrderCount=18

Count - Grouped

public void Linq77() 
{ 
    List<Product> products = GetProductList(); 
  
    var categoryCounts = 
        from p in products 
        group p by p.Category into g 
        select new { Category = g.Key, ProductCount = g.Count() }; 
  
    ObjectDumper.Write(categoryCounts 
}

 

Result
Category=Beverages ProductCount=12
Category=Condiments ProductCount=5
Category=Produce ProductCount=6
Category=Meat/Poultry ProductCount=12
Category=Seafood ProductCount=10
Category=Dairy Products ProductCount=13
Category=Confections ProductCount=7
Category=Grains/Cereals ProductCount=12

Sum - Simple

public void Linq78() 
{ 
    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 
  
    double numSum = numbers.Sum(); 
  
    Console.WriteLine("The sum of the numbers is {0}.", numSum); 
}
Result

The sum of the numbers is 45.

Sum - Projection

public void Linq79() 
{ 
    string[] words = { "cherry", "apple", "blueberry" }; 
  
    double totalChars = words.Sum(w => w.Length); 
  
    Console.WriteLine("There are a total of {0} characters in these words.", totalChars); 
}
Result

There are a total of 20 characters in these words.

Sum - Grouped

public void Linq80() 
{ 
    List<Product> products = GetProductList(); 
  
    var categories = 
        from p in products 
        group p by p.Category into g 
        select new { Category = g.Key, TotalUnitsInStock = g.Sum(p => p.UnitsInStock) }; 
  
    ObjectDumper.Write(categories); 
}

Result
Category=Beverages TotalUnitsInStock=559
Category=Condiments TotalUnitsInStock=507
Category=Produce TotalUnitsInStock=100
Category=Meat/Poultry TotalUnitsInStock=165
Category=Seafood TotalUnitsInStock=701
Category=Dairy Products TotalUnitsInStock=393
Category=Confections TotalUnitsInStock=386
Category=Grains/Cereals TotalUnitsInStock=308

Min - Simple

public void Linq81() 
{ 
    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 
  
    int minNum = numbers.Min(); 
  
    Console.WriteLine("The minimum number is {0}.", minNum); 
}
Result

The minimum number is 0.

Min - Projection

ublic void Linq82() 
{ 
    string[] words = { "cherry", "apple", "blueberry" }; 
  
    int shortestWord = words.Min(w => w.Length); 
  
    Console.WriteLine("The shortest word is {0} characters long.", shortestWord); 
}
Result

The shortest word is 5 characters long.

Min - Grouped

public void Linq83() 
{ 
    List<Product> products = GetProductList(); 
  
    var categories = 
        from p in products 
        group p by p.Category into g 
        select new { Category = g.Key, CheapestPrice = g.Min(p => p.UnitPrice) }; 
  
    ObjectDumper.Write(categories); 
}

 

Result
Category=Beverages CheapestPrice=4.5000
Category=Condiments CheapestPrice=10.0000
Category=Produce CheapestPrice=10.0000
Category=Meat/Poultry CheapestPrice=7.4500
Category=Seafood CheapestPrice=6.0000
Category=Dairy Products CheapestPrice=2.5000
Category=Confections CheapestPrice=9.2000
Category=Grains/Cereals CheapestPrice=7.0000

Min - Elements

public void Linq84() 
{ 
    List<Product> products = GetProductList(); 
  
    var categories = 
        from p in products 
        group p by p.Category into g 
        let minPrice = g.Min(p => p.UnitPrice) 
        select new { Category = g.Key, CheapestProducts = g.Where(p => p.UnitPrice == minPrice) }; 
  
    ObjectDumper.Write(categories, 1); 
}
Result

Category=Beverages      CheapestProducts=... 
  CheapestProducts: ProductID=24  ProductName=Guaraná Fantástica  Category=Beverages      UnitPrice=4.5000        UnitsInStock=20 
Category=Condiments    CheapestProducts=... 
  CheapestProducts: ProductID=3  ProductName=Aniseed Syrup      Category=Condiments    UnitPrice=10.0000      UnitsInStock=13 
Category=Produce        CheapestProducts=... 
  CheapestProducts: ProductID=74  ProductName=Longlife Tofu      Category=Produce        UnitPrice=10.0000      UnitsInStock=4 
Category=Meat/Poultry  CheapestProducts=... 
  CheapestProducts: ProductID=54  ProductName=Tourtière  Category=Meat/Poultry  UnitPrice=7.4500        UnitsInStock=21 
Category=Seafood        CheapestProducts=... 
  CheapestProducts: ProductID=13  ProductName=Konbu      Category=Seafood        UnitPrice=6.0000        UnitsInStock=24 
Category=Dairy Products        CheapestProducts=... 
  CheapestProducts: ProductID=33  ProductName=Geitost    Category=Dairy Products        UnitPrice=2.5000        UnitsInStock=112 
Category=Confections    CheapestProducts=... 
  CheapestProducts: ProductID=19  ProductName=Teatime Chocolate Biscuits  Category=Confections    UnitPrice=9.2000        UnitsInStock=25 
Category=Grains/Cereals        CheapestProducts=... 
  CheapestProducts: ProductID=52  ProductName=Filo Mix    Category=Grains/Cereals        UnitPrice=7.0000        UnitsInStock=38

Max - Simple

public void Linq85() 
{ 
    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 
  
    int maxNum = numbers.Max(); 
  
    Console.WriteLine("The maximum number is {0}.", maxNum); 
}
Result

The maximum number is 9.

Max - Projection

public void Linq86() 
{ 
    string[] words = { "cherry", "apple", "blueberry" }; 
  
    int longestLength = words.Max(w => w.Length); 
  
    Console.WriteLine("The longest word is {0} characters long.", longestLength); 
}
Result

The longest word is 9 characters long.

Max - Grouped

public void Linq87() 
{ 
    List<Product> products = GetProductList(); 
  
    var categories = 
        from p in products 
        group p by p.Category into g 
        select new { Category = g.Key, MostExpensivePrice = g.Max(p => p.UnitPrice) }; 
  
    ObjectDumper.Write(categories); 
}

Result
Category=Beverages MostExpensivePrice=263.5000
Category=Condiments MostExpensivePrice=43.9000
Category=Produce MostExpensivePrice=53.0000
Category=Meat/Poultry MostExpensivePrice=123.7900
Category=Seafood MostExpensivePrice=62.5000
Category=Dairy Products MostExpensivePrice=55.0000
Category=Confections MostExpensivePrice=81.0000
Category=Grains/Cereals MostExpensivePrice=38.0000

Max - Elements

public void Linq88() 
{ 
    List<Product> products = GetProductList(); 
  
    var categories = 
        from p in products 
        group p by p.Category into g 
        let maxPrice = g.Max(p => p.UnitPrice) 
        select new { Category = g.Key, MostExpensiveProducts = g.Where(p => p.UnitPrice == maxPrice) }; 
  
    ObjectDumper.Write(categories, 1); 
}
Result

Category=Beverages      MostExpensiveProducts=... 
  MostExpensiveProducts: ProductID=38    ProductName=Côte de Blaye      Category=Beverages      UnitPrice=263.5000      UnitsInStock=17 
Category=Condiments    MostExpensiveProducts=... 
  MostExpensiveProducts: ProductID=63    ProductName=Vegie-spread        Category=Condiments    UnitPrice=43.9000      UnitsInStock=24 
Category=Produce        MostExpensiveProducts=... 
  MostExpensiveProducts: ProductID=51    ProductName=Manjimup Dried Apples      Category=Produce        UnitPrice=53.0000      UnitsInStock=20 
Category=Meat/Poultry  MostExpensiveProducts=... 
  MostExpensiveProducts: ProductID=29    ProductName=Thüringer Rostbratwurst    Category=Meat/Poultry  UnitPrice=123.7900      UnitsInStock=0 
Category=Seafood        MostExpensiveProducts=... 
  MostExpensiveProducts: ProductID=18    ProductName=Carnarvon Tigers    Category=Seafood        UnitPrice=62.5000      UnitsInStock=42 
Category=Dairy Products        MostExpensiveProducts=... 
  MostExpensiveProducts: ProductID=59    ProductName=Raclette Courdavault        Category=Dairy Products        UnitPrice=55.0000      UnitsInStock=79 
Category=Confections    MostExpensiveProducts=... 
  MostExpensiveProducts: ProductID=20    ProductName=Sir Rodney's Marmalade      Category=Confections    UnitPrice=81.0000      UnitsInStock=40 
Category=Grains/Cereals        MostExpensiveProducts=... 
  MostExpensiveProducts: ProductID=56    ProductName=Gnocchi di nonna Alice      Category=Grains/Cereals        UnitPrice=38.0000      UnitsInStock=21

Average - Simple

public void Linq89() 
{ 
    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 
  
    double averageNum = numbers.Average(); 
  
    Console.WriteLine("The average number is {0}.", averageNum); 
}
Result

The average number is 4.5.

Average - Projection

public void Linq90() 
{ 
    string[] words = { "cherry", "apple", "blueberry" }; 
  
    double averageLength = words.Average(w => w.Length); 
  
    Console.WriteLine("The average word length is {0} characters.", averageLength); 
}
Result

The average word length is 6.66666666666667 characters.

Average - Grouped

public void Linq91() 
{ 
    List<Product> products = GetProductList(); 
  
    var categories = 
        from p in products 
        group p by p.Category into g 
        select new { Category = g.Key, AveragePrice = g.Average(p => p.UnitPrice) }; 
  
    ObjectDumper.Write(categories); 
}

Result

Category=Beverages AveragePrice=37.979166666666666666666666667
Category=Condiments AveragePrice=23.0625
Category=Produce AveragePrice=32.3700
Category=Meat/Poultry AveragePrice=54.006666666666666666666666667
Category=Seafood AveragePrice=20.6825
Category=Dairy Products AveragePrice=28.7300
Category=Confections AveragePrice=25.1600
Category=Grains/Cereals AveragePrice=20.2500

Aggregate - Simple

这个例子是数组中所有的元素相乘,求出最终的积

public void Linq92() 
{ 
    double[] doubles = { 1.7, 2.3, 1.9, 4.1, 2.9 }; 
  
    double product = doubles.Aggregate((runningProduct, nextFactor) => runningProduct * nextFactor); 
  
    Console.WriteLine("Total product of all numbers: {0}", product); 
}

Result

Total product of all numbers: 88.33081

Aggregate - Seed

public void Linq93() 
{ 
    double startBalance = 100.0; 
  
    int[] attemptedWithdrawals = { 20, 10, 40, 50, 10, 70, 30 }; 
  
    double endBalance = 
        attemptedWithdrawals.Aggregate(startBalance, 
            (balance, nextWithdrawal) => 
                ((nextWithdrawal <= balance) ? (balance - nextWithdrawal) : balance)); 
  
    Console.WriteLine("Ending balance: {0}", endBalance); 
}

Result

Ending balance: 20

Concat - 1

求二个集合的合集

public void Linq94() 
{ 
    int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 }; 
    int[] numbersB = { 1, 3, 5, 7, 8 }; 
  
    var allNumbers = numbersA.Concat(numbersB); 
  
    Console.WriteLine("All numbers from both arrays:"); 
    foreach (var n in allNumbers) 
    { 
        Console.WriteLine(n); 
    } 
}

Result

All numbers from both arrays: 











8

Concat - 2

public void Linq95() 
{ 
    List<Customer> customers = GetCustomerList(); 
    List<Product> products = GetProductList(); 
  
    var customerNames = 
        from c in customers 
        select c.CompanyName; 
    var productNames = 
        from p in products 
        select p.ProductName; 
  
    var allNames = customerNames.Concat(productNames); 
  
    Console.WriteLine("Customer and product names:"); 
    foreach (var n in allNames) 
    { 
        Console.WriteLine(n); 
    } 
} 
Result

 

Customer and product names:
Alfreds Futterkiste
Ana Trujillo Emparedados y helados
Antonio Moreno Taquería
Around the Horn
Berglunds snabbköp
Blauer See Delikatessen
Blondel père et fils
Bólido Comidas preparadas
Bon app'
Bottom-Dollar Markets
B's Beverages
Cactus Comidas para llevar
Centro comercial Moctezuma
Chop-suey Chinese
Comércio Mineiro
Consolidated Holdings
Drachenblut Delikatessen
Du monde entier
Eastern Connection
Ernst Handel
Familia Arquibaldo
FISSA Fabrica Inter. Salchichas S.A.
Folies gourmandes
Folk och fä HB
Frankenversand
France restauration

EqualAll - 1

public void Linq96() 
{ 
    var wordsA = new string[] { "cherry", "apple", "blueberry" }; 
    var wordsB = new string[] { "cherry", "apple", "blueberry" }; 
  
    bool match = wordsA.SequenceEqual(wordsB); 
  
    Console.WriteLine("The sequences match: {0}", match); 
} 

Result

 

The sequences match: True

EqualAll - 2

public void Linq97() 
{ 
    var wordsA = new string[] { "cherry", "apple", "blueberry" }; 
    var wordsB = new string[] { "apple", "blueberry", "cherry" }; 
  
    bool match = wordsA.SequenceEqual(wordsB); 
  
    Console.WriteLine("The sequences match: {0}", match); 
} 

Result

The sequences match: False

Combine

public static class CustomSequenceOperators 
{ 
    public static IEnumerable Combine(this IEnumerable first, IEnumerable second,  
    Func func) { 
        using (IEnumerator e1 = first.GetEnumerator(), e2 = second.GetEnumerator()) 
        { 
            while (e1.MoveNext() && e2.MoveNext()) { 
                yield return func(e1.Current, e2.Current); 
            } 
        } 
    } 
} 
 
public void Linq98() {             
    int[] vectorA = { 0, 2, 4, 5, 6 }; 
    int[] vectorB = { 1, 3, 5, 7, 8 }; 
     
    int dotProduct = vectorA.Combine(vectorB, (a, b) => a * b).Sum(); 
     
    Console.WriteLine("Dot product: {0}", dotProduct); 
}

Result

Dot product: 109

Deferred Execution

public void Linq99() 
{ 
    // Sequence operators form first-class queries that 
    // are not executed until you enumerate over them. 
  
    int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 
  
    int i = 0; 
    var q = 
        from n in numbers 
        select ++i; 
  
    // Note, the local variable 'i' is not incremented 
    // until each element is evaluated (as a side-effect): 
    foreach (var v in q) 
    { 
        Console.WriteLine("v = {0}, i = {1}", v, i); 
    } 
}
Result

v = 1, i = 1
v = 2, i = 2
v = 3, i = 3
v = 4, i = 4
v = 5, i = 5
v = 6, i = 6
v = 7, i = 7
v = 8, i = 8
v = 9, i = 9
v = 10, i = 10

 

Immediate Execution

public void Linq100() 
{ 
    // Methods like ToList() cause the query to be 
    // executed immediately, caching the results. 
  
    int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 
  
    int i = 0; 
    var q = ( 
        from n in numbers 
        select ++i) 
        .ToList(); 
  
    // The local variable i has already been fully 
    // incremented before we iterate the results: 
    foreach (var v in q) 
    { 
        Console.WriteLine("v = {0}, i = {1}", v, i); 
    } 
} 

Result

v = 1, i = 10
v = 2, i = 10
v = 3, i = 10
v = 4, i = 10
v = 5, i = 10
v = 6, i = 10
v = 7, i = 10
v = 8, i = 10
v = 9, i = 10
v = 10, i = 10

Query Reuse

public void Linq101() 
{ 
    // Deferred execution lets us define a query once 
    // and then reuse it later after data changes. 
  
    int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 
    var lowNumbers = 
        from n in numbers 
        where n <= 3 
        select n; 
  
    Console.WriteLine("First run numbers <= 3:"); 
    foreach (int n in lowNumbers) 
    { 
        Console.WriteLine(n); 
    } 
  
    for (int i = 0; i < 10; i++) 
    { 
        numbers[i] = -numbers[i]; 
    } 
  
    // During this second run, the same query object, 
    // lowNumbers, will be iterating over the new state 
    // of numbers[], producing different results: 
    Console.WriteLine("Second run numbers <= 3:"); 
    foreach (int n in lowNumbers) 
    { 
        Console.WriteLine(n); 
    } 
} 
Result

First run numbers <= 3:
1
3
2
0
Second run numbers <= 3:
-5
-4
-1
-3
-9
-8
-6
-7
-2
0

Cross Join

public void Linq102() 
{ 
  
    string[] categories = new string[]{  
        "Beverages",   
        "Condiments",   
        "Vegetables",   
        "Dairy Products",   
        "Seafood" };  
  
    List<Product> products = GetProductList(); 
  
    var q = 
        from c in categories 
        join p in products on c equals p.Category 
        select new { Category = c, p.ProductName }; 
 
    foreach (var v in q) 
    { 
        Console.WriteLine(v.ProductName + ": " + v.Category);  
    } 
}

Result

Chai: Beverages
Chang: Beverages
Guaraná Fantástica: Beverages
Sasquatch Ale: Beverages
Steeleye Stout: Beverages
Côte de Blaye: Beverages
Chartreuse verte: Beverages
Ipoh Coffee: Beverages
Laughing Lumberjack Lager: Beverages
Outback Lager: Beverages
Rhönbräu Klosterbier: Beverages
Lakkalikööri: Beverages
Aniseed Syrup: Condiments
Chef Anton's Cajun Seasoning: Condiments
Chef Anton's Gumbo Mix: Condiments
Grandma's Boysenberry Spread: Condiments
Northwoods Cranberry Sauce: Condiments
Genen Shouyu: Condiments
Gula Malacca: Condiments
Sirop d'érable: Condiments
Vegie-spread: Condiments

Group Join

public void Linq103() 
{ 
    string[] categories = new string[]{  
        "Beverages",  
        "Condiments",  
        "Vegetables",  
        "Dairy Products",  
        "Seafood" }; 
  
    List<Product> products = GetProductList(); 
  
    var q = 
        from c in categories 
        join p in products on c equals p.Category into ps 
        select new { Category = c, Products = ps }; 
  
    foreach (var v in q) 
    { 
        Console.WriteLine(v.Category + ":"); 
        foreach (var p in v.Products) 
        { 
            Console.WriteLine("   " + p.ProductName); 
        } 
    } 
}

Result

Beverages:
Chai
Chang
Guaraná Fantástica
Sasquatch Ale
Steeleye Stout
Côte de Blaye
Chartreuse verte
Ipoh Coffee
Laughing Lumberjack Lager
Outback Lager
Rhönbräu Klosterbier
Lakkalikööri
Condiments:
Aniseed Syrup
Chef Anton's Cajun Seasoning
Chef Anton's Gumbo Mix
Grandma's Boysenberry Spread
Northwoods Cranberry Sauce

Cross Join with Group Join

public void Linq104() 
{ 
    string[] categories = new string[]{   
        "Beverages",  
        "Condiments",  
        "Vegetables", 
        "Dairy Products",   
        "Seafood" }; 
  
    List<Product> products = GetProductList(); 
  
  
  
    var q = 
        from c in categories 
        join p in products on c equals p.Category into ps 
        from p in ps 
        select new { Category = c, p.ProductName }; 
  
    foreach (var v in q) 
    { 
        Console.WriteLine(v.ProductName + ": " + v.Category); 
    } 
}

Result

Chai: Beverages
Chang: Beverages
Guaraná Fantástica: Beverages
Sasquatch Ale: Beverages
Steeleye Stout: Beverages
Côte de Blaye: Beverages
Chartreuse verte: Beverages
Ipoh Coffee: Beverages
Laughing Lumberjack Lager: Beverages
Outback Lager: Beverages
Rhönbräu Klosterbier: Beverages
Lakkalikööri: Beverages
Aniseed Syrup: Condiments
Chef Anton's Cajun Seasoning: Condiments
Chef Anton's Gumbo Mix: Condiments
Grandma's Boysenberry Spread: Condiments
Northwoods Cranberry Sauce: Condiments
Genen Shouyu: Condiments
Gula Malacca: Condiments
Sirop d'érable: Condiments
Vegie-spread: Condiments

Left Outer Join

public void Linq105()  
{ 
    string[] categories = new string[]{   
        "Beverages",  
        "Condiments",   
        "Vegetables",   
        "Dairy Products",  
        "Seafood" }; 
  
    List<Product> products = GetProductList(); 
  
  
  
    var q = 
        from c in categories 
        join p in products on c equals p.Category into ps 
        from p in ps.DefaultIfEmpty() 
        select new { Category = c, ProductName = p == null ? "(No products)" : p.ProductName }; 
  
    foreach (var v in q) 
    { 
        Console.WriteLine(v.ProductName + ": " + v.Category); 
    } 
}

Result

Chai: Beverages
Chang: Beverages
Guaraná Fantástica: Beverages
Sasquatch Ale: Beverages
Steeleye Stout: Beverages
Côte de Blaye: Beverages
Chartreuse verte: Beverages
Ipoh Coffee: Beverages
Laughing Lumberjack Lager: Beverages
Outback Lager: Beverages
Rhönbräu Klosterbier: Beverages
Lakkalikööri: Beverages
Aniseed Syrup: Condiments
Chef Anton's Cajun Seasoning: Condiments
Chef Anton's Gumbo Mix: Condiments
Grandma's Boysenberry Spread: Condiments
Northwoods Cranberry Sauce: Condiments
Genen Shouyu: Condiments
Gula Malacca: Condiments

posted @ 2015-07-18 17:04  生有涯而知无涯  阅读(1322)  评论(0编辑  收藏  举报