SortedList的使用示例

Posted 无懈可击

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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();
}

}

以上是关于SortedList的使用示例的主要内容,如果未能解决你的问题,请参考以下文章

SortedList排序列表

c#的SortedList使用方法

为啥Java中没有SortedList?

.Net 数据结构:ArrayList、List、HashTable、Dictionary、SortedList、SortedDictionary——速度、内存以及何时使用它们? [关闭]

《C#零基础入门之百识百例》(八十九)SortedList和SortedDictionary介绍 --对比解析

LINQ 计算 SortedList<dateTime,double> 的移动平均值