AddRange
AddRange
是一个在集合操作中非常常用的方法,用于将多个元素一次性添加到集合中。它广泛应用于各种集合类型,如 List<T>
、HashSet<T>
、Dictionary<TKey, TValue>
等。以下是对 AddRange
方法的详细解释和一些示例。1. List<T>.AddRange
List<T>
是一个动态数组,提供了 AddRange
方法,用于一次性添加多个元素。方法签名
csharp
public void AddRange(IEnumerable<T> collection);
-
参数:
collection
是一个IEnumerable<T>
,表示要添加的元素集合。 -
作用:将
collection
中的所有元素添加到List<T>
中。
示例代码
csharp
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
List<int> list = new List<int> { 1, 2, 3 };
// 使用 AddRange 添加多个元素
list.AddRange(new int[] { 4, 5, 6 });
// 输出结果
foreach (var item in list)
{
Console.WriteLine(item);
}
}
}
输出结果
1
2
3
4
5
6
2. HashSet<T>.AddRange
HashSet<T>
是一个集合,提供了 AddRange
方法,用于一次性添加多个元素。HashSet<T>
确保集合中的元素是唯一的。方法签名
csharp
public void AddRange(IEnumerable<T> collection);
-
参数:
collection
是一个IEnumerable<T>
,表示要添加的元素集合。 -
作用:将
collection
中的所有元素添加到HashSet<T>
中,重复的元素会被忽略。
示例代码
csharp
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
HashSet<int> hashSet = new HashSet<int> { 1, 2, 3 };
// 使用 AddRange 添加多个元素
hashSet.AddRange(new int[] { 3, 4, 5 });
// 输出结果
foreach (var item in hashSet)
{
Console.WriteLine(item);
}
}
}
输出结果
1
2
3
4
5
3. Dictionary<TKey, TValue>.AddRange
Dictionary<TKey, TValue>
是一个键值对集合,提供了 AddRange
方法,用于一次性添加多个键值对。需要注意的是,Dictionary<TKey, TValue>
本身没有 AddRange
方法,但可以通过扩展方法实现。扩展方法
csharp
using System;
using System.Collections.Generic;
using System.Linq;
public static class DictionaryExtensions
{
public static void AddRange<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, IEnumerable<KeyValuePair<TKey, TValue>> collection)
{
foreach (var kvp in collection)
{
dictionary.Add(kvp.Key, kvp.Value);
}
}
}
class Program
{
static void Main(string[] args)
{
Dictionary<int, string> dict = new Dictionary<int, string>
{
{ 1, "one" },
{ 2, "two" }
};
// 使用扩展方法 AddRange 添加多个键值对
dict.AddRange(new Dictionary<int, string>
{
{ 3, "three" },
{ 4, "four" }
});
// 输出结果
foreach (var kvp in dict)
{
Console.WriteLine($"{kvp.Key}: {kvp.Value}");
}
}
}
输出结果
1: one
2: two
3: three
4: four
4. AddRange
的优点
-
高效性:一次性添加多个元素,避免了多次调用
Add
方法的开销。 -
简洁性:代码更加简洁,易于阅读和维护。
-
灵活性:适用于多种集合类型,如
List<T>
、HashSet<T>
、Dictionary<TKey, TValue>
等。
5. 注意事项
-
重复元素:在
HashSet<T>
中,重复的元素会被忽略。 -
键值对冲突:在
Dictionary<TKey, TValue>
中,如果键已经存在,会抛出ArgumentException
。 -
性能:对于非常大的集合,一次性添加大量元素可能会有一定的性能开销,需要合理使用。
6. 总结
AddRange
是一个非常实用的方法,用于一次性将多个元素添加到集合中。它广泛应用于 List<T>
、HashSet<T>
等集合类型,并可以通过扩展方法应用于 Dictionary<TKey, TValue>
。通过合理使用 AddRange
,可以提高代码的效率和可读性