[英]How to get the Key and the Value of Dictionary<int, string> returned from method
I'm collecting data dynamically and I've chosen Dictionary<int, string>
as data structure to store this data. 我正在动态收集数据,并且选择了
Dictionary<int, string>
作为数据结构来存储此数据。
At the beginning of my method I declare a variable : 在我的方法开始时,我声明了一个变量:
Dictionary<int, string> templatesKeyName = new Dictionary<int, string>();
at the end of the method I want templatesKeyName
to contains all pairs of int (ids) and Names relevent for this request. 在方法的末尾,我希望
templatesKeyName
包含此请求的所有对int(id)和Names relevent。 So for example I have: 例如,我有:
private static Dictionary<int, string> GetTemplateForUserWithAccount()
{
Dictionary<int, string> kv = new Dictionary<int, string>();
//populate the `kv` dictionary
return kv;
}
and I want to be able to do something like: 而且我希望能够执行以下操作:
if(Client.Accounts.Count > 0)
{
templatesKeyName.Add(GetTemplateForUserWithAccount());
}
Obviously .Add()
extension expects two arguments but I wasn't able to find out how can I pass the values from the method without writing first assigning the result to e temporary Dictionary and then iterating with foreach
.Also, most likely I will get single result most of the time so iteration is not something that I consider really. 显然
.Add()
扩展名需要两个参数,但是我无法找出如何从方法中传递值,而无需首先将结果分配给e临时Dictionary,然后使用foreach
进行迭代。此外,我很可能会得到大多数情况下都是单一结果,因此迭代并不是我真正考虑的东西。
You can create an extension method for that: 您可以为此创建扩展方法:
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);
}
}
And use it like the following: 并按如下所示使用它:
templatesKeyName.AddRange(GetTemplateForUserWithAccount());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.