【问题标题】:C#;setting key and values in dictionary with tuple of stringsC#;使用字符串元组在字典中设置键和值
【发布时间】:2017-10-01 13:29:42
【问题描述】:

我对 C# 很陌生,所以请相应地指导。我有这个声明:

Dictionary<string, Tuple<string, string>> myDictionary = new Dictionary<string, Tuple<string, string>>();

我想将元组的键和字段设置为:

myDictionary.Add( myKey, Tuple<firstValue, secondValue> );

其中 firstValue 和 secondValue 是字符串,它们将成为另一个字典的键。我想要一些关于 .Add() 方法中元组初始化语法的帮助。

【问题讨论】:

    标签: c# dictionary initialization tuples


    【解决方案1】:

    试试这个:

    Dictionary<string, Tuple<string, string>> myDictionary = new Dictionary<string, Tuple<string, string>>();
    
    myDictionary.Add(myKey, new Tuple<string, string>(firstValue, secondValue));
    

    需要调用 Tuple 的构造函数。

    【讨论】:

    • Tuple.Create() 通常看起来更容易一些。
    【解决方案2】:
        Dictionary<string, Tuple<string, string>> myDictionary = new Dictionary<string, Tuple<string, string>>();
    
    myDictionary.Add("key", new Tuple<string, string>("firstValue", "secondValue"));
    

    【讨论】:

    • 感谢 M. Pillapan。正是我需要的。作为参考,我错过了在 Add 方法中将 Tuple 声明为 code 的概念。
    猜你喜欢
    • 2017-10-06
    • 1970-01-01
    • 2021-09-07
    • 2018-09-11
    • 2021-08-02
    • 2017-08-24
    • 2019-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多