Thứ Ba, 12 tháng 2, 2008

Làm thế nào để tạo một Block Iterator cho một danh sách các số nguyên

Trong ví dụ này, một mảng các số nguyên được sử dụng để xây dựng danh sách SampleCollection. Một cho vòng lặp duyệt qua bộ sưu tập trở lại và mang lại giá trị của mỗi mục. Sau đó, một vòng lặp foreach được sử dụng để hiển thị các mục của bộ sưu tập.

// Declare the collection:
public class SampleCollection
{
        public int[] items;

        public SampleCollection()
        {
                  items = new int[5] { 5, 4, 7, 9, 3 };
        }

        public System.Collections.IEnumerable BuildCollection()
        {
                 for (int i = 0; i < items.Length; i++)
                {
                       yield return items[i];
               }
       }
}

class MainClass
{
       static void Main()
       {
                 SampleCollection col = new SampleCollection();

                // Display the collection items:
                System.Console.WriteLine("Values in the collection are:");
                foreach (int i in col.BuildCollection())
                {
                        System.Console.Write(i + " ");
                }

               // Keep the console window open in debug mode.
               System.Console.WriteLine("Press any key to exit.");
               System.Console.ReadKey();
       }
}
/* Output:
Values in the collection are:
5 4 7 9 3
*/

DangTrung.

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

Đăng nhận xét