如何将 KeyValuePair 转换为字典,因为 ToDictionary 在 c# 中不可用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18955384/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:40:19  来源:igfitidea点击:

How to convert KeyValuePair to Dictionary as ToDictionary is not available in c#?

c#

提问by Robin Joseph

How to convert KeyValuePairto Dictionary, since ToDictionaryis not available in C#?

如何转换KeyValuePair为字典,因为ToDictionary在 C# 中不可用?

采纳答案by jwg

var dictionary = new Dictionary<string, object> { { kvp.Key, kvp.Value } };

ToDictionarydoesexist in C# (edit: not the same ToDictionaryyou were thinking of) and can be used like this:

ToDictionary确实存在于 C# 中(编辑:与ToDictionary您想的不一样)并且可以这样使用:

var list = new List<KeyValuePair<string, object>>{kvp};
var dictionary = list.ToDictionary(x => x.Key, x => x.Value);

Here listcould be a Listor other IEnumerableof anything. The first lambda shows how to extract the key from a list item, and the second shows how to extract the value. In this case they are both trivial.

这里list可能是一个List或其他IEnumerable任何东西。第一个 lambda 显示如何从列表项中提取键,第二个显示如何提取值。在这种情况下,它们都是微不足道的。

回答by JSJ

Create a collection of KeyValuePairand make sure System.Linq is imported in a usingstatement.

创建一个KeyValuePair集合并确保 System.Linq 在using语句中导入。

Then you will be able to see the .ToDictionary()extension method.

然后你就可以看到 . ToDictionary()扩展方法。

public IList<KeyValuePair<string, object>> MyDictionary { get; set; }

回答by br1

Implement it yourself as an extension method.

自己将其实现为扩展方法。

public static class MyExtensions
{

    public static Dictionary<T1,T2> ToDictionary<T1, T2>(this KeyValuePair<T1, T2> kvp)
    {
      var dict = new Dictionary<T1, T2>();
      dict.Add(kvp.Key, kvp.Value);
      return dict;
    }

}

see this in action: https://dotnetfiddle.net/Ka54t7

看看这个:https: //dotnetfiddle.net/Ka54t7

回答by BartoszKP

If I understand correctly you can do it as follows:

如果我理解正确,您可以按如下方式进行:

new[] { keyValuePair }.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

回答by Simon Whitehead

Alternatively (if you can't use Linq.. although I'm curious why..).. implement ToDictionaryyourself...

或者(如果你不能使用 Linq ......虽然我很好奇为什么......)..ToDictionary自己实现......

public static Dictionary<TKey, TElement> ToDictionary<TSource, TKey, TElement>(IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector) {
    if (source == null)
    {
        throw new ArgumentNullException("source");
    }
    if (keySelector == null) {
        throw new ArgumentNullException("keySelector");
    }
    if (elementSelector == null) {
        throw new ArgumentNullException("elementSelector");
    }

    var dictionary = new Dictionary<TKey, TElement>();
    foreach (TSource current in source) {
        dictionary.Add(keySelector(current), elementSelector(current));
    }
    return dictionary;
}

Example usage:

用法示例:

var kvpList = new List<KeyValuePair<int, string>>(){
    new KeyValuePair<int, string>(1, "Item 1"),
    new KeyValuePair<int, string>(2, "Item 2"),
};

var dict = ToDictionary(kvpList, x => x.Key, x => x.Value);