Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

Generic Collections ใน C# (List, SortedList)

Generic Collections ใน C# ได้แก่ List<T>, SortedList<TKey, TValue> ฯลฯ

List<T>

Generic Collection ขนาดไดนามิก ต่างจาก ArrayList (Non-generic)

ตัวอย่าง List

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<string> myList = new List<string>() { "one", "two", "three", "four", "five", "six" };
        Console.WriteLine(myList.Count); // 6
    }
}

SortedList

ผสม Array และ Hash Table มี Item เรียงตาม Key เข้าถึงได้ทั้ง Key และ Index

ตัวอย่าง SortedList

using System;
using System.Collections;

namespace CollectionsApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            SortedList sl = new SortedList();
            sl.Add("001", "Tim"); sl.Add("002", "Steve");
            sl.Add("003", "Bill"); sl.Add("004", "Tom");
            if (sl.ContainsValue("Bill"))
                Console.WriteLine("This name is already in the list");
            else
                sl.Add("005", "James");
            ICollection key = sl.Keys;
            foreach (string k in key) Console.WriteLine(k + ": " + sl[k]);
        }
    }
}

Output

This name is already in the list
001: Tim
002: Steve
003: Bill
004: Tom