从 IEnumerable 重新创建字典>

发布于 2022-07-28 22:59:53

我有一个返回 的方法IEnumerable<KeyValuePair<string, ArrayList>>,但是一些调用者要求方法的结果是字典。如何将其转换IEnumerable<KeyValuePair<string, ArrayList>>为 aDictionary<string, ArrayList>以便我可以使用TryGetValue

方法:

public IEnumerable<KeyValuePair<string, ArrayList>> GetComponents()
{
  // ...
  yield return new KeyValuePair<string, ArrayList>(t.Name, controlInformation);
}

呼叫者:

Dictionary<string, ArrayList> actual = target.GetComponents();
actual.ContainsKey("something");
关注者
0
被浏览
17
1 个回答
  • 面试哥
    面试哥 2022-07-28
    为面试而生,有面试问题,就找面试哥。

    如果您使用 .NET 3.5 或 .NET 4,使用 LINQ 创建字典很容易:

    Dictionary<string, ArrayList> result = target.GetComponents()
                                          .ToDictionary(x => x.Key, x => x.Value);
    

    没有 a 这样的东西,IEnumerable<T1, T2>但是 aKeyValuePair<TKey, TValue>很好。



推荐阅读
知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看