SortedList的使用示例


代碼

public class TestSortedList
{
public static void Main()
{

// 創建一個SortedList對象
SortedList mySL = new SortedList();
mySL.Add("First", "Hello");
mySL.Add("Second", "World");
mySL.Add("Third", "!");
//列舉SortedList的屬性、鍵、值
Console.WriteLine("mySL");
Console.WriteLine(" Count: {0}", mySL.Count);
Console.WriteLine(" Capacity: {0}", mySL.Capacity);
Console.WriteLine(" Keys and Values:");
PrintIndexAndKeysAndValues(mySL);

#region SortedList獲得鍵、值列表
SortedList mySL1 = new SortedList();
mySL1.Add(1.3, "fox");
mySL1.Add(1.4, "jumped");
mySL1.Add(1.5, "over");
mySL1.Add(1.2, "brown");
mySL1.Add(1.1, "quick");
mySL1.Add(1.0, "The");
mySL1.Add(1.6, "the");
mySL1.Add(1.8, "dog");
mySL1.Add(1.7, "lazy");

//獲得指定索引處的鍵和值
int myIndex = 3;
Console.WriteLine("The key at index {0} is {1}.", myIndex, mySL1.GetKey(myIndex));
Console.WriteLine("The value at index {0} is {1}.", myIndex, mySL1.GetByIndex(myIndex));

// 獲得SortedList中的鍵列表和值列表
IList myKeyList = mySL1.GetKeyList();
IList myValueList = mySL1.GetValueList();

// Prints the keys in the first column and the values in the second column.
Console.WriteLine("\t-KEY-\t-VALUE-");
for (int i = 0; i < mySL1.Count; i++)
Console.WriteLine("\t{0}\t{1}", myKeyList[i], myValueList[i]);

#endregion

#region 為SortedList中的元素重新賦值
// Creates and initializes a new SortedList.
SortedList mySL2 = new SortedList();
mySL2.Add(2, "two");
mySL2.Add(3, "three");
mySL2.Add(1, "one");
mySL2.Add(0, "zero");
mySL2.Add(4, "four");

// 打印顯示列表的鍵和值
Console.WriteLine("The SortedList contains the following values:");
PrintIndexAndKeysAndValues(mySL2);

// 獲得指定鍵的索引
int myKey = 2;
Console.WriteLine("The key \"{0}\" is at index {1}.", myKey, mySL2.IndexOfKey(myKey));

// 獲得指定值的索引
String myValue = "three";
Console.WriteLine("The value \"{0}\" is at index {1}.", myValue, mySL2.IndexOfValue(myValue));


// 重新設置指定索引處的值
mySL2.SetByIndex(3, "III");
mySL2.SetByIndex(4, "IV");

//打印顯示列表的鍵和值
Console.WriteLine("After replacing the value at index 3 and index 4,");
PrintIndexAndKeysAndValues(mySL2);
#endregion

Console.ReadKey();

}

//打印SortedList中的鍵和值
public static void PrintIndexAndKeysAndValues(SortedList myList)
{
Console.WriteLine("\t-INDEX-\t-KEY-\t-VALUE-");
for (int i = 0; i < myList.Count; i++)
{
Console.WriteLine("\t[{0}]:\t{1}\t{2}", i, myList.GetKey(i), myList.GetByIndex(i));
}
Console.WriteLine();
}

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM