Recreating a Dictionary from an IEnumerable>

后端 未结 2 356
执笔经年
执笔经年 2020-12-02 12:02

I have a method that returns an IEnumerable>, but some of the callers require the result of the method to be a dicti

相关标签:
2条回答
  • 2020-12-02 12:14

    As of .NET Core 2.0, the constructor Dictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>) now exists.

    0 讨论(0)
  • 2020-12-02 12:27

    If you're using .NET 3.5 or .NET 4, it's easy to create the dictionary using LINQ:

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

    There's no such thing as an IEnumerable<T1, T2> but a KeyValuePair<TKey, TValue> is fine.

    0 讨论(0)
提交回复
热议问题