lea*_*tes 165 c# collections ienumerable dictionary idictionary
我有一个返回的方法IEnumerable<KeyValuePair<string, ArrayList>>
,但有些调用者要求方法的结果是字典.如何将其IEnumerable<KeyValuePair<string, ArrayList>>
转换为Dictionary<string, ArrayList>
可以使用的TryGetValue
?
方法:
public IEnumerable<KeyValuePair<string, ArrayList>> GetComponents()
{
// ...
yield return new KeyValuePair<string, ArrayList>(t.Name, controlInformation);
}
Run Code Online (Sandbox Code Playgroud)
呼叫者:
Dictionary<string, ArrayList> actual = target.GetComponents();
actual.ContainsKey("something");
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 311
如果您使用的是.NET 3.5或.NET 4,则可以使用LINQ轻松创建字典:
Dictionary<string, ArrayList> result = target.GetComponents()
.ToDictionary(x => x.Key, x => x.Value);
Run Code Online (Sandbox Code Playgroud)
没有这样的东西,IEnumerable<T1, T2>
但是a KeyValuePair<TKey, TValue>
很好.
归档时间: |
|
查看次数: |
88353 次 |
最近记录: |