代码
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(" -KEY- -VALUE-");
for (int i = 0; i < mySL1.Count; i++)
Console.WriteLine(" {0} {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(" -INDEX- -KEY- -VALUE-");
for (int i = 0; i < myList.Count; i++)
{
Console.WriteLine(" [{0}]: {1} {2}", i, myList.GetKey(i), myList.GetByIndex(i));
}
Console.WriteLine();
}
}