SortedList是C#中的一种数据结构,它提供了键-值对的存储方式,并根据键的值自动排序。SortedList在需要按照键的顺序访问元素的情况下非常有用。
排序列表是数组和散列表的组合。它包含可以使用键或索引访问的项列表。如果你使用索引访问项目,它是一个数组列表,如果你使用键访问项目,它是一个哈希表。项的集合总是按键值排序。
创建SortedList
SortedList<string, int> sortedList = new SortedList<string, int>();
向SortedList中添加元素
sortedList.Add("apple", 1);
sortedList.Add("banana", 2);
sortedList.Add("cherry", 3);
访问SortedList中的元素
int apple = sortedList["apple"];
检查SortedList中是否包含某个键
bool containsKey = sortedList.ContainsKey("banana");
遍历SortedList中的所有元素:
foreach (KeyValuePair<string, int> pair in sortedList)
{
Console.WriteLine("Key: {0}, Value: {1}", pair.Key, pair.Value);
}
需求:需要按照字母顺序存储和检索水果的名称和它们的数量。
这就可以使用SortedList来实现这个功能
示例代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SortedList1
{
internal class Program
{
static void Main(string[] args)
{
SortedList<string, int> fruits = new SortedList<string, int>();
fruits.Add("apple", 10);
fruits.Add("banana", 5);
fruits.Add("cherry", 8);
Console.WriteLine("有多少苹果?: " + fruits["apple"]);
Console.WriteLine("有多少草莓?: " + fruits["cherry"]);
Console.WriteLine("有多少香蕉?: " + fruits["banana"]);
}
}
}
仔细看运行结果三色标识
完整示例代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SortedList2
{
internal class Program
{
static void Main(string[] args)
{
// 创建一个SortedList
SortedList<string, int> sortedList = new SortedList<string, int>();
// 向SortedList中添加元素
sortedList.Add("apple", 1);
sortedList.Add("banana", 2);
sortedList.Add("cherry", 3);
// 输出SortedList中的所有元素
foreach (KeyValuePair<string, int> pair in sortedList)
{
Console.WriteLine("Key: {0}, Value: {1}", pair.Key, pair.Value);
}
// 从SortedList中获取一个元素
int apple = sortedList["apple"];
Console.WriteLine("The value for 'apple' is: {0}", apple);
// 检查SortedList中是否包含某个键
bool containsKey = sortedList.ContainsKey("banana");
Console.WriteLine("SortedList contains 'banana': {0}", containsKey);
}
}
}
/*首先创建一个SortedList,然后向其中添加了一些元素。
由于SortedList会自动根据键排序,所以当我们遍历SortedList时,元素会按照键的字母顺序输出。
还有如何从SortedList中获取一个元素的值,以及如何检查SortedList是否包含某个键。
*/