Thứ Bảy, 14 tháng 2, 2009

Làm thế nào để tạo ra các nhóm lồng nhau trong một biểu thức truy vấn LINQ

Ví dụ sau đây cho thấy làm thế nào để tạo ra các nhóm lồng nhau trong một biểu thức truy vấn LINQ. Mỗi nhóm được tạo ra theo năm học hoặc trình độ lớp sau đó được chia nhỏ thành các nhóm dựa trên tên của cá nhân.

public void QueryNestedGroups()
{
         var queryNestedGroups = from student in students  
                    group student by student.Year into newGroup1
                    from newGroup2 in
                           (from student in newGroup1  group student by student.LastName)
                    group newGroup2 by newGroup1.Key;


         // Three nested foreach loops are required to iterate
         // over all elements of a grouped group. Hover the mouse
         // cursor over the iteration variables to see their actual type.
         foreach (var outerGroup in queryNestedGroups)
         {
                 Console.WriteLine("DataClass.Student Level = {0}", outerGroup.Key);
                 foreach (var innerGroup in outerGroup)
                {
                        Console.WriteLine("\tNames that begin with: {0}", innerGroup.Key);
                        foreach (var innerGroupElement in innerGroup)
                       {
                               Console.WriteLine("\t\t{0} {1}", innerGroupElement.LastName, innerGroupElement.FirstName);
                       }
               }
        }
}

Lưu ý rằng ba vòng lặp foreach lồng nhau được yêu cầu phải duyệt qua các yếu tố bên trong của một nhóm lồng nhau.

DangTrung

Không có nhận xét nào:

Đăng nhận xét