C#中SortedList如何一次性添加多个键值对?
在C#中批量向SortedList添加键值对的方法
你遇到的错误原因很明确:SortedList的Add方法仅支持传入单个键和对应的值两个参数,你传入三个参数自然会触发编译错误。
下面是两种常见的批量添加键值对的实现方式:
1. 创建SortedList时批量初始化
这是你已经在使用的方式,通过集合初始化器可以一次性指定多个键值对,语法简洁且合法:
SortedList sortedList = new SortedList() { { "Ind", "India" }, { "BD", "Bangladesh" }, { "SA", "South Africa" } };
如果使用泛型版本的SortedList<TKey, TValue>(推荐,类型更安全,避免装箱拆箱操作),写法类似:
var sortedList = new SortedList<string, string>() { { "Ind", "India" }, { "BD", "Bangladesh" } };
2. 已创建的SortedList批量添加新键值对
如果要给已经初始化好的SortedList追加多个键值对,没有内置的AddRange方法,但可以通过以下两种方式实现:
方式一:编写扩展方法
自己实现一个AddRange扩展方法,复用性更高:
// 非泛型SortedList的扩展方法 public static class SortedListExtensions { public static void AddRange(this SortedList sortedList, IEnumerable<DictionaryEntry> entries) { foreach (var entry in entries) { sortedList.Add(entry.Key, entry.Value); } } // 泛型SortedList<TKey, TValue>的扩展方法(推荐) public static void AddRange<TKey, TValue>(this SortedList<TKey, TValue> sortedList, IEnumerable<KeyValuePair<TKey, TValue>> pairs) { foreach (var pair in pairs) { sortedList.Add(pair.Key, pair.Value); } } }
使用时只需传入键值对集合即可:
// 给非泛型SortedList添加 var newEntries = new List<DictionaryEntry> { new DictionaryEntry("Hel", "Hello"), new DictionaryEntry("Wld", "World") }; sortedList.AddRange(newEntries); // 给泛型SortedList添加 var newPairs = new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("Hel", "Hello"), new KeyValuePair<string, string>("Wld", "World") }; sortedList.AddRange(newPairs);
方式二:手动循环添加
如果不想写扩展方法,直接通过循环遍历键值对集合逐个添加也可以:
var newItems = new Dictionary<string, string> { { "Hel", "Hello" }, { "Wld", "World" } }; foreach (var item in newItems) { sortedList.Add(item.Key, item.Value); }
注意:无论哪种方式,都要确保添加的键不存在于SortedList中,否则会抛出
ArgumentException(因为SortedList不允许重复键)。
内容的提问来源于stack exchange,提问作者Fozle Rabbi
相关产品推荐
相关产品推荐

