LINQ 使用方法


  1. int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
  2.  
  3.     var lowNums =
  4.         from n in numbers
  5.         where n < 5
  6.         select n;
  1. List<Product> products = GetProductList();
  2.  
  3.     var soldOutProducts =
  4.         from p in products
  5.         where p.UnitsInStock == 0
  6.         select p;
  7.  
  1.  List<Product> products = GetProductList();
  2.  
  3.     var expensiveInStockProducts =
  4.         from p in products
  5.         where p.UnitsInStock > 0 && p.UnitPrice > 3.00M
  6.         select p;
  1.  List<Customer> customers = GetCustomerList();
  2.  
  3.     var waCustomers =
  4.         from c in customers
  5.         where c.Region == "WA"
  6.         select c;
  1. string[] digits = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
  2.  
  3.     var shortDigits = digits.Where((digit, index) => digit.Length < index);
  1. int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
  2.  
  3.     var numsPlusOne =
  4.         from n in numbers
  5.         select n + 1;
  1.  List<Product> products = GetProductList();
  2.  
  3.     var productNames =
  4.         from p in products
  5.         select p.ProductName;
  1. int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
  2.     string[] strings = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
  3.  
  4.     var textNums =
  5.         from n in numbers
  6.         select strings[n];
  1. string[] words = { "aPPLE", "BlUeBeRrY", "cHeRry" };
  2.  
  3.     var upperLowerWords =
  4.         from w in words
  5.         select new { Upper = w.ToUpper(), Lower = w.ToLower() };
  1.   int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
  2.     string[] strings = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
  3.  
  4.     var digitOddEvens =
  5.         from n in numbers
  6.         select new { Digit = strings[n], Even = (n % 2 == 0) };
  1. int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
  2.  
  3.     var numsInPlace = numbers.Select((num, index) => new { Num = num, InPlace = (num == index) });
  1.   int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
  2.     string[] digits = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
  3.  
  4.     var lowNums =
  5.         from n in numbers
  6.         where n < 5
  7.         select digits[n];
  1.  int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };
  2.     int[] numbersB = { 1, 3, 5, 7, 8 };
  3.  
  4.     var pairs =
  5.         from a in numbersA
  6.         from b in numbersB
  7.         where a < b
  8.         select new { a, b };
  1.  List<Customer> customers = GetCustomerList();
  2.  
  3.     var orders =
  4.         from c in customers
  5.         from o in c.Orders
  6.         where o.Total < 500.00M
  7.         select new { c.CustomerID, o.OrderID, o.Total };
  1.     List<Customer> customers = GetCustomerList();
  2.  
  3.     var orders =
  4.         from c in customers
  5.         from o in c.Orders
  6.         where o.OrderDate >= new DateTime(1998, 1, 1)
  7.         select new { c.CustomerID, o.OrderID, o.OrderDate };
  1. List<Customer> customers = GetCustomerList();
  2.  
  3.     var orders =
  4.         from c in customers
  5.         from o in c.Orders
  6.         where o.Total >= 2000.0M
  7.         select new { c.CustomerID, o.OrderID, o.Total };
  1.  List<Customer> customers = GetCustomerList();
  2.  
  3.     DateTime cutoffDate = new DateTime(1997, 1, 1);
  4.  
  5.     var orders =
  6.         from c in customers
  7.         where c.Region == "WA"
  8.         from o in c.Orders
  9.         where o.OrderDate >= cutoffDate
  10.         select new { c.CustomerID, o.OrderID };
  1.  List<Customer> customers = GetCustomerList();
  2.  
  3.     var customerOrders =
  4.         customers.SelectMany(
  5.             (cust, custIndex) =>
  6.             cust.Orders.Select(o => "Customer #" + (custIndex + 1) +
  7.                                     " has an order with OrderID " + o.OrderID));
  1.     int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
  2.     var first3Numbers = numbers.Take(3);

 

  1.  int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
  2.     var allButFirst4Numbers = numbers.Skip(4);

 

All but first 4 numbers: 





0

 

  1.  List<Customer> customers = GetCustomerList();
  2.  
  3.  
  4.  
  5.     var waOrders =
  6.         from c in customers 
  7.         from o in c.Orders 
  8.         where c.Region == "WA" 
  9.         select new { c.CustomerID, o.OrderID, o.OrderDate };
  10.      var allButFirst2Orders = waOrders.Skip(2);

 

  1. int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
  2.     var firstNumbersLessThan6 = numbers.TakeWhile(n => n < 6);

 

  1.  int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
  2.     var firstSmallNumbers = numbers.TakeWhile((n, index) => n >= index);
  1.  int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
  2.     var allButFirst3Numbers = numbers.SkipWhile(n => n % 3 != 0);

3
9
8
6
7
2

  1.     int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
  2.     var laterNumbers = numbers.SkipWhile((n, index) => n >= index);
  1.  string[] words = { "blueberry", "chimpanzee", "abacus", "banana", "apple", "cheese" };
  2.  
  3.     var wordGroups =
  4.         from w in words
  5.         group w by w[0] into g
  6.         select new { FirstLetter = g.Key, Words = g };
  7.  
  8.     foreach (var g in wordGroups)
  9.     {
  10.         Console.WriteLine("Words that start with the letter '{0}':", g.FirstLetter);
  11.         foreach (var w in g.Words)
  12.         {
  13.             Console.WriteLine(w);
  14.         }
  15.     }
  1.     List<Product> products = GetProductList();
  2.  
  3.     var orderGroups =
  4.         from p in products
  5.         group p by p.Category into g
  6.         select new { Category = g.Key, Products = g };
  7.  
  8.     ObjectDumper.Write(orderGroups, 1);
  1. List<Customer> customers = GetCustomerList();
  2.  
  3.     var customerOrderGroups =
  4.         from c in customers
  5.         select
  6.             new
  7.             {
  8.                 c.CompanyName,
  9.                 YearGroups =
  10.                     from o in c.Orders
  11.                     group o by o.OrderDate.Year into yg
  12.                     select
  13.                         new
  14.                         {
  15.                             Year = yg.Key,
  16.                             MonthGroups =
  17.                                 from o in yg
  18.                                 group o by o.OrderDate.Month into mg
  19.                                 select new { Month = mg.Key, Orders = mg }
  20.                         }
  21.             };

GroupBy - Comparer

This sample uses GroupBy to partition trimmed elements of an array using a custom comparer that matches words that are anagrams of each other.

1.      public void Linq44()
2.      {
3.          string[] anagrams = { "from   ", " salt", " earn ", "  last   ", " near ", " form  " };
4.       
5.          var orderGroups = anagrams.GroupBy(w => w.Trim(), new AnagramEqualityComparer());
6.       
7.          ObjectDumper.Write(orderGroups, 1);
8.      }
9.       
10.  public class AnagramEqualityComparer : IEqualityComparer<string>
11.  {
12.      public bool Equals(string x, string y)
13.      {
14.          return getCanonicalString(x) == getCanonicalString(y);
15.      }
16.   
17.      public int GetHashCode(string obj)
18.      {
19.          return getCanonicalString(obj).GetHashCode();
20.      }
21.   
22.      private string getCanonicalString(string word)
23.      {
24.          char[] wordChars = word.ToCharArray();
25.          Array.Sort<char>(wordChars);
26.          return new string(wordChars);
27.      }
28.  }

Result

...
from 
form 
...
salt
last 
...
earn 
near

GroupBy - Comparer, Mapped

This sample uses GroupBy to partition trimmed elements of an array using a custom comparer that matches words that are anagrams of each other, and then converts the results to uppercase.

1.      public void Linq45()
2.      {
3.          string[] anagrams = { "from   ", " salt", " earn ", "  last   ", " near ", " form  " };
4.       
5.          var orderGroups = anagrams.GroupBy(
6.                      w => w.Trim(),
7.                      a => a.ToUpper(),
8.                      new AnagramEqualityComparer()
9.                      );
10.   
11.      ObjectDumper.Write(orderGroups, 1);
12.  }
13.   
14.  public class AnagramEqualityComparer : IEqualityComparer<string>
15.  {
16.      public bool Equals(string x, string y)
17.      {
18.          return getCanonicalString(x) == getCanonicalString(y);
19.      }
20.   
21.      public int GetHashCode(string obj)
22.      {
23.          return getCanonicalString(obj).GetHashCode();
24.      }
25.   
26.      private string getCanonicalString(string word)
27.      {
28.          char[] wordChars = word.ToCharArray();
29.          Array.Sort<char>(wordChars);
30.          return new string(wordChars);
31.      }
32.  }

Result

...
FROM 
FORM 
...
SALT
LAST 
...
EARN 
NEAR

原文地址:https://www.cnblogs.com/senion/p/LINQ.html