Như bài trước mình đã giới thiệu khía quát về LINQ cũng như cách tạo , kết nối CSDL với LINQ, hôm nay mình xin chia sẽ với các bạn về lệnh Select trong LINQ.
Như trong SQL lệnh Select chúng ta có thể hiểu là “Lấy”, các bạn sẽ hiểu rõ hơn ở những đoạn Code Sample phía sau :
Select – Simple 1
1: public void Linq6()
2: {
3: int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
4:
5: var numsPlusOne =
6: from n in numbers
7: select n + 1;
8:
9: Console.WriteLine("Numbers + 1:");
10: foreach (var i in numsPlusOne)
11: {
12: Console.WriteLine(i);
13: }
14: }
Result
Numbers + 1:
6
5
2
4
10
9
7
8
3
1
Select – Simple 2
1: public void Linq7()
2: {
3: List<Product> products = GetProductList();
4:
5: var productNames =
6: from p in products
7: select p.ProductName;
8:
9: Console.WriteLine("Product Names:");
10: foreach (var productName in productNames)
11: {
12: Console.WriteLine(productName);
13: }
14: }
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
Mishi Kobe Niku …..
Select – Transformation
1: public void Linq8()
2: {
3: int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
4: string[] strings = { "zero", "one", "two", "three", "four",
5: "five", "six", "seven", "eight", "nine" };
6: var textNums =
7: from n in numbers
8: select strings[n];
9:
10: Console.WriteLine("Number strings:");
11: foreach (var s in textNums)
12: {
13: Console.WriteLine(s);
14: }
15: }
Result
Number strings:
five
four
one
three
nine
eight
six
seven
two
zero
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:
5: var upperLowerWords =
6: from w in words
7: select new { Upper = w.ToUpper(), Lower = w.ToLower() };
8:
9: foreach (var ul in upperLowerWords)
10: {
11: Console.WriteLine("Uppercase: {0}, Lowercase: {1}", ul.Upper, ul.Lower);
12: }
13: }
Result
Uppercase: APPLE, Lowercase: apple
Uppercase: BLUEBERRY, Lowercase: blueberry
Uppercase: CHERRY, Lowercase: cherry
Select – Anonymous Types 2
This sample uses select to produce a sequence containing text representations of digits and whether their length is even or odd
1: public void Linq10()
2: {
3: int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
4: string[] strings = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
5:
6: var digitOddEvens =
7: from n in numbers
8: select new { Digit = strings[n], Even = (n % 2 == 0) };
9:
10: foreach (var d in digitOddEvens)
11: {
12: Console.WriteLine("The digit {0} is {1}.", d.Digit, d.Even ? "even" : "odd");
13: }
14: }
Result
The digit five is odd.
The digit four is even.
The digit one is odd.
The digit three is odd.
The digit nine is odd.
The digit eight is even.
The digit six is even.
The digit seven is odd.
The digit two is even.
The digit zero is even.
Select – Anonymous Types 3
1: public void Linq11()
2: {
3: List<Product> products = GetProductList();
4:
5: var productInfos =
6: from p in products
7: select new { p.ProductName, p.Category, Price = p.UnitPrice };
8:
9: Console.WriteLine("Product Info:");
10: foreach (var productInfo in productInfos)
11: {
12: Console.WriteLine("{0} is in the category {1} and costs {2} per unit.", productInfo.ProductName, productInfo.Category, productInfo.Price);
13: }
14: }
Result
Product Info:
Chai is in the category Beverages and costs 18.0000 per unit.
Chang is in the category Beverages and costs 19.0000 per unit.
Aniseed Syrup is in the category Condiments and costs 10.0000 per unit.
Chef Anton’s Cajun Seasoning is in the category Condiments and costs 22.0000 per unit.
Chef Anton’s Gumbo Mix is in the category Condiments and costs 21.3500 per unit.
Grandma’s Boysenberry Spread is in the category Condiments and costs 25.0000 per unit.
Uncle Bob’s Organic Dried Pears is in the category Produce and costs 30.0000 per unit.
Northwoods Cranberry Sauce is in the category Condiments and costs 40.0000 per unit.
Mishi Kobe Niku is in the category Meat/Poultry and costs 97.0000 per unit.
Ikura is in the category Seafood and costs 31.0000 per unit.
Queso Cabrales is in the category Dairy Products and costs 21.0000 per unit.
Queso Manchego La Pastora is in the category Dairy Products and costs 38.0000 per unit.
Konbu is in the category Seafood and costs 6.0000 per unit.
….
Select – Indexed
This sample uses an indexed Select clause to determine if the value of ints in an array match their position in the array.
1: public void Linq12()
2: {
3: int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
4:
5: var numsInPlace = numbers.Select((num, index) => new { Num = num, InPlace = (num == index) });
6:
7: Console.WriteLine("Number: In-place?");
8: foreach (var n in numsInPlace)
9: {
10: Console.WriteLine("{0}: {1}", n.Num, n.InPlace);
11: }
12: }
Result
Number: In-place?
5: False
4: False
1: False
3: True
9: False
8: False
6: True
7: True
2: False
0: False
Select – Filtered
This sample combines select and where to make a simple query that returns the text form of each digit less than 5.
1: public void Linq13()
2: {
3: int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
4: string[] digits = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
5:
6: var lowNums =
7: from n in numbers
8: where n < 5
9: select digits[n];
10:
11: Console.WriteLine("Numbers < 5:");
12: foreach (var num in lowNums)
13: {
14: Console.WriteLine(num);
15: }
16: }
Result
Numbers < 5:
four
one
three
two
zero
SelectMany – Compound from 1
This sample uses a compound from clause to make a query that returns all pairs of numbers from both arrays such that the number from numbersA is less than the number from numbersB.
1: public void Linq14()
2: {
3: int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };
4: int[] numbersB = { 1, 3, 5, 7, 8 };
5:
6: var pairs =
7: from a in numbersA
8: from b in numbersB
9: where a < b
10: select new { a, b };
11:
12: Console.WriteLine("Pairs where a < b:");
13: foreach (var pair in pairs)
14: {
15: Console.WriteLine("{0} is less than {1}", pair.a, pair.b);
16: }
17: }
Result
Pairs where a < b:
0 is less than 1
0 is less than 3
0 is less than 5
0 is less than 7
0 is less than 8
2 is less than 3
2 is less than 5
2 is less than 7
2 is less than 8
4 is less than 5
4 is less than 7
4 is less than 8
5 is less than 7
5 is less than 8
6 is less than 7
6 is less than 8
SelectMany – Compound from 2
This sample uses a compound from clause to select all orders where the order total is less than 500.00
1: public void Linq15()
2: {
3: List<Customer> customers = GetCustomerList();
4:
5: var orders =
6: from c in customers
7: from o in c.Orders
8: where o.Total < 500.00M
9: select new { c.CustomerID, o.OrderID, o.Total };
10:
11: ObjectDumper.Write(orders);
12: }
Result
CustomerID=ALFKI OrderID=10702 Total=330.00
CustomerID=ALFKI OrderID=10952 Total=471.20
CustomerID=ANATR OrderID=10308 Total=88.80
CustomerID=ANATR OrderID=10625 Total=479.75
CustomerID=ANATR OrderID=10759 Total=320.00
CustomerID=ANTON OrderID=10365 Total=403.20
CustomerID=ANTON OrderID=10682 Total=375.50
CustomerID=AROUT OrderID=10355 Total=480.00
CustomerID=AROUT OrderID=10453 Total=407.70
CustomerID=AROUT OrderID=10741 Total=228.00
CustomerID=AROUT OrderID=10743 Total=319.20
……………………..
SelectMany – from Assignment
This sample uses a compound from clause to select all orders where the order total is greater than 2000.00 and uses from assignment to avoid requesting the total twice.
1: public void Linq17()
2: {
3: List<Customer> customers = GetCustomerList();
4:
5: var orders =
6: from c in customers
7: from o in c.Orders
8: where o.Total >= 2000.0M
9: select new { c.CustomerID, o.OrderID, o.Total };
10:
11: ObjectDumper.Write(orders);
12: }
Result
CustomerID=ANTON OrderID=10573 Total=2082.00
CustomerID=AROUT OrderID=10558 Total=2142.90
CustomerID=AROUT OrderID=10953 Total=4441.25
CustomerID=BERGS OrderID=10384 Total=2222.40
CustomerID=BERGS OrderID=10524 Total=3192.65
CustomerID=BERGS OrderID=10672 Total=3815.25
……
Với những VD trên mình tin chắc rằng các bạn đã hiểu rõ hơn về lệnh Select trong LINQ
Chúc các bạn thành công