Đang chuẩn bị liên kết để tải về tài liệu:
Apress Accelerated C 2010_11
Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ
Tải xuống
using System; using System.Linq; public class GroupExample { static void Main() { int[] numbers = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; // Partition numbers into odd and // even numbers. var query = from x in numbers group x by x % 2 into partition where partition.Key == 0 select new { Key = partition.Key, Count = partition.Count(), Group = partition }; foreach( var item in query ) { Console.WriteLine( "mod2 == {0}", item.Key ); Console.WriteLine( "Count == {0}", item.Count ); foreach( var number in item.Group ) { Console.Write( "{0}, ", number ); }. | CHAPTER 16 LINQ LANGUAGE INTEGRATED QUERY using System using System.Linq public class GroupExample . static void Main int numbers . 0 1 2 3 4 5 6 7 8 9 Partition numbers into odd and even numbers. var query from x in numbers group x by x 2 into partition where partition.Key 0 select new Key partition.Key Count partition.Count Group partition foreach var item in query Console.WriteLine mod2 0 item.Key Console.WriteLine Count 0 item.Count foreach var number in item.Group Console.Write 0 number . . . . Console.WriteLine n In this query the continuation the part of the query after the into clause filters the series of groups where Key is 0 by using a where clause. This filters out the group of even numbers. I then project that group out into an anonymous type producing a count of items in the group to go along with the Key property and the items in the group. Thus the output to the console includes only one group. But what if I wanted to add a count to each group in the partition As I said before the into clause is a generator. So I can produce the desired result by changing the query to this var query from x in numbers group x by x 2 into partition select new Key partition.Key Count partition.Count Group partition Notice that I removed the where clause thus removing any filtering. When executed with this version of the query the example produces the following desired output mod2 0 561 CHAPTER 16 LINQ LANGUAGE INTEGRATED QUERY Count 5 0 2 4 6 8 mod2 1 Count 5 1 3 5 7 9 In both of the previous query expressions note that the result is not an IEnumerable IGrouping T as it commonly is when the group clause is the final projector. Rather the end result is an IEnumerable T where T is replaced with our anonymous type. The Virtues of Being Lazy When you build a LINQ query expression and assign it to a query variable very little code is executed in that statement. The data becomes available only when you iterate over that query variable which executes the query once for each .