我有一个字典,里面有一些值,比如说:
Animals <string, string>
Run Code Online (Sandbox Code Playgroud)
我现在收到另一个类似的字典,说:
NewAnimals <string,string>
Run Code Online (Sandbox Code Playgroud)
如何将整个NewAnimals字典附加到动物?
Cod*_*aos 97
foreach(var newAnimal in NewAnimals)
Animals.Add(newAnimal.Key,newAnimal.Value)
Run Code Online (Sandbox Code Playgroud)
注意:这会在重复键上引发异常.
或者,如果你真的想要去的扩展方法途径(我不会),那么你可以定义一个通用AddRange的是在任何工作的扩展方法ICollection<T>,而不是仅仅对Dictionary<TKey,TValue>.
public static void AddRange<T>(this ICollection<T> target, IEnumerable<T> source)
{
if(target==null)
throw new ArgumentNullException(nameof(target));
if(source==null)
throw new ArgumentNullException(nameof(source));
foreach(var element in source)
target.Add(element);
}
Run Code Online (Sandbox Code Playgroud)
(抛出字典的重复键)
Gab*_*abe 33
创建一个扩展方法很可能你想要多次使用它,这可以防止重复的代码.
执行:
public static void AddRange<T, S>(this Dictionary<T, S> source, Dictionary<T, S> collection)
{
if (collection == null)
{
throw new ArgumentNullException("Collection is null");
}
foreach (var item in collection)
{
if(!source.ContainsKey(item.Key)){
source.Add(item.Key, item.Value);
}
else
{
// handle duplicate key issue here
}
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
Dictionary<string,string> animals = new Dictionary<string,string>();
Dictionary<string,string> newanimals = new Dictionary<string,string>();
animals.AddRange(newanimals);
Run Code Online (Sandbox Code Playgroud)
最明显的方法是:
foreach(var kvp in NewAnimals)
Animals.Add(kvp.Key, kvp.Value);
//use Animals[kvp.Key] = kvp.Value instead if duplicate keys are an issue
Run Code Online (Sandbox Code Playgroud)
由于Dictionary<TKey, TValue>显式实现了该ICollection<KeyValuePair<TKey, TValue>>.Add方法,您还可以这样做:
var animalsAsCollection = (ICollection<KeyValuePair<string, string>>) Animals;
foreach(var kvp in NewAnimals)
animalsAsCollection.Add(kvp);
Run Code Online (Sandbox Code Playgroud)
遗憾的是,班级没有AddRange像List<T>这样的方法.
| 归档时间: |
|
| 查看次数: |
110426 次 |
| 最近记录: |