如何获取从方法</int,>返回的Dictionary <int,string =“”>的键和值

时间:2014-11-10 11:14:40

标签: c# dictionary

我正在动态收集数据,我选择了Dictionary<int, string>作为数据结构来存储这些数据。

在我的方法开始时,我声明了一个变量:

Dictionary<int, string> templatesKeyName = new Dictionary<int, string>();

在方法的最后,我希望templatesKeyName包含此请求的所有int(id)和Names对的对。例如,我有:

private static Dictionary<int, string> GetTemplateForUserWithAccount()
{
Dictionary<int, string> kv = new Dictionary<int, string>();
//populate the `kv` dictionary
return kv;
}

我希望能够做到这样的事情:

if(Client.Accounts.Count > 0)
{
  templatesKeyName.Add(GetTemplateForUserWithAccount());
}

显然.Add()扩展需要两个参数但是我无法找到如何在不首先将结果分配给e临时Dictionary然后使用foreach进行迭代的情况下传递方法中的值。而且,我很可能在大部分时间都会获得单一结果,所以迭代不是我认为真的。

1 个答案:

答案 0 :(得分:1)

您可以为此创建扩展方法:

public static void AddRange<T,K>(this Dictionary<T,K> source, IEnumerable<KeyValuePair<T,K>> values)
{
    foreach(var kvp in values)
    {
       if(!source.ContainsKey(kvp.Key))
          source.Add(kvp.Key, kvp.Value);
    }
}

使用它如下:

templatesKeyName.AddRange(GetTemplateForUserWithAccount());
相关问题