Nhóm :
Member
Tham gia:
09-09-2010
Bài viết:
7
Lần thăm:
57

Select - LINQ Samples

Ví dụ 1: 

  1. public void Linq6()
  2. {
  3. int[] numbers = { 5413986720 };
  4.     var numsPlusOne =
  5.         from n in numbers
  6.         select n + 1;
  7.     Console.WriteLine("Numbers + 1:");
  8. foreach (var i in numsPlusOne)
  9.     {
  10.         Console.WriteLine(i);
  11.     }
  12. }

Result

Numbers + 1:
6
5
2
4
10
9
7
8
3
1

Ví dụ 2:

This sample uses select to return a sequence of just the names of a list of products.

  1. public void Linq7()
  2. {
  3.     List<Product> products = GetProductList();
  4.     var productNames =
  5.         from p in products
  6.         select p.ProductName;
  7.     Console.WriteLine("Product Names:");
  8. foreach (var productName in productNames)
  9.     {
  10.         Console.WriteLine(productName);
  11.     }
  12. }

Result

Product Names:
Chai
Chang
Aniseed Syrup
Chef Anton's Cajun Seasoning
Chef Anton's Gumbo Mix
Grandma's Boysenberry Spread
Uncle Bob's Organic Dried Pears

Northwoods Cranberry Sauce 

Ví dụ 3:

Select - Transformation

This sample uses select to produce a sequence of strings representing the text version of a sequence of ints.

  1. public void Linq8()
  2. {
  3. int[] numbers = { 5413986720 };
  4. string[] strings = { "zero""one""two""three""four""five""six""seven""eight""nine" };
  5.     var textNums =
  6.         from n in numbers
  7.         select strings[n];
  8.     Console.WriteLine("Number strings:");
  9. foreach (var s in textNums)
  10.     {
  11.         Console.WriteLine(s);
  12.     }
  13. }

Result

Number strings:
five
four
one
three
nine
eight
six
seven
two
zero 

 Ví dụ 4: 

Select - Anonymous Types 1

This sample uses select to produce a sequence of the uppercase and lowercase versions of each word in the original array.

  1. public void Linq9()
  2. {
  3. string[] words = { "aPPLE""BlUeBeRrY""cHeRry" };
  4.     var upperLowerWords =
  5.         from w in words
  6.         select new { Upper = w.ToUpper(), Lower = w.ToLower() };
  7. foreach (var ul in upperLowerWords)
  8.     {
  9.         Console.WriteLine("Uppercase: {0}, Lowercase: {1}", ul.Upper, ul.Lower);
  10.     }
  11. }

Result

Uppercase: APPLE, Lowercase: apple
Uppercase: BLUEBERRY, Lowercase: blueberry

Uppercase: CHERRY, Lowercase: cherry






Tỷ thượng bất túc tỷ hạ hữu dư, tri túc thường lạc [hihi]