Select - LINQ Samples
Ví dụ 1:
- public void Linq6()
- {
- int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
- var numsPlusOne =
- from n in numbers
- select n + 1;
- Console.WriteLine("Numbers + 1:");
- foreach (var i in numsPlusOne)
- {
- Console.WriteLine(i);
- }
- }
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.
- public void Linq7()
- {
- List<Product> products = GetProductList();
- var productNames =
- from p in products
- select p.ProductName;
- Console.WriteLine("Product Names:");
- foreach (var productName in productNames)
- {
- Console.WriteLine(productName);
- }
- }
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
Ví dụ 3:
Select - Transformation
This sample uses select to produce a sequence of strings representing the text version of a sequence of ints.
- public void Linq8()
- {
- int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
- string[] strings = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
- var textNums =
- from n in numbers
- select strings[n];
- Console.WriteLine("Number strings:");
- foreach (var s in textNums)
- {
- Console.WriteLine(s);
- }
- }
Result
Number strings:
five
four
one
three
nine
eight
six
seven
two
zero
Ví dụ 4:
Uppercase: CHERRY, Lowercase: cherry
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.
- public void Linq9()
- {
- string[] words = { "aPPLE", "BlUeBeRrY", "cHeRry" };
- var upperLowerWords =
- from w in words
- select new { Upper = w.ToUpper(), Lower = w.ToLower() };
- foreach (var ul in upperLowerWords)
- {
- Console.WriteLine("Uppercase: {0}, Lowercase: {1}", ul.Upper, ul.Lower);
- }
- }
Result
Uppercase: APPLE, Lowercase: apple
Uppercase: BLUEBERRY, Lowercase: blueberry
Tỷ thượng bất túc tỷ hạ hữu dư, tri túc thường lạc [hihi]