📜  C#|在SortedList对象中获取值(1)

📅  最后修改于: 2023-12-03 15:30:17.505000             🧑  作者: Mango

在SortedList对象中获取值

SortedList是C#中的一个集合类型,它以键值对的形式存储数据,并且使用键对集合中的元素进行排序。

要在SortedList对象中获取值,我们可以使用[]操作符或者GetByIndex方法。

使用[]操作符获取值

使用[]操作符获取SortedList对象中的值需要指定键名。如果该键名不存在,则会引发一个异常。

下面是一个示例代码:

SortedList mySortedList = new SortedList();

mySortedList.Add("apple", "A fruit");
mySortedList.Add("orange", "A fruit too");
mySortedList.Add("carrot", "A vegetable");

// 请注意: 当使用‘[]’操作符获取值时,如果键名不存在,将会抛出异常
Console.WriteLine(mySortedList["apple"]); // 输出 "A fruit"

在上面的代码中,我们创建了一个SortedList对象,并添加了三个元素。然后使用[]操作符获取apple键的值,并输出在控制台上。

如果你想避免[]操作符引发的异常,你可以使用Contains方法检查指定键是否存在。

if (mySortedList.Contains("banana"))
{
    Console.WriteLine(mySortedList["banana"]); // 如果key存在,输出对应的value
}
else
{
    Console.WriteLine("banana does not exist in mySortedList");
}
使用GetByIndex方法获取值

GetByIndex方法用于按照索引获取值,索引从0开始计数。GetByIndex方法的返回类型是object,因此需要进行类型转换。该方法也可以避免访问不存在键名引发的异常。下面是一个示例代码:

SortedList mySortedList = new SortedList();

mySortedList.Add("apple", "A fruit");
mySortedList.Add("orange", "A fruit too");
mySortedList.Add("carrot", "A vegetable");

// 使用GetByIndex方法获取值
Console.WriteLine((string)mySortedList.GetByIndex(1)); // 输出 "A fruit too"

在上面的代码中,我们创建了一个SortedList对象,并添加了三个元素。然后使用GetByIndex(1)方法获取值,并进行类型转换。

总结

使用[]操作符或GetByIndex方法可以在SortedList对象中获取值。如果使用[]操作符访问不存在的键名,将会引发异常,需要进行有效检查。而GetByIndex方法则可以避免这个问题。