字典<字符串,列表<键值对<字符串,字符串>>>



我已经创建了:

Dictionary<string, List <KeyValuePair<string,string>>> diction = new Dictionary<string, List<KeyValuePair<string,string>>>();

后来我添加了该列表:

diction.Add(firststring, new List<KeyValuePair<string,string>>());
diction[firststring].Add(new KeyValuePair<string, string>(1ststringlist, 2ndstringlist));

现在,如果我想在屏幕上阅读并显示此词典,我该如何处理foreach循环?就像3个Dimmension语法,现在不要如何创建并访问它。

也可以解释如何阅读此部分?

diction[firststring].Add

这是什么标记[]的意思是什么?我在那里读了整个字典?

谢谢您的回答和时间。

字典商店 key / value pairs。在您的情况下,您的密钥类型是string,值类型为List <KeyValuePair<string,string>>

diction[firststring]

firststring是您的Key,您正在尝试访问List <KeyValuePair<string,string>>。您认为您的最佳选择是嵌套循环。如果您想显示所有值。例如:

foreach(var key in dict.Keys)
{
   // dict[key] returns List <KeyValuePair<string,string>>
   foreach(var value in dict[key])
   {
      // here type of value is  KeyValuePair<string,string>
      var currentValue = value.Value;
      var currentKey = value.Key;
   }
}

用于打印数据架构,尝试以下操作:

// string.Join(separator, enumerable) concatenates the enumerable together with 
// the separator string
var result = string.Join(
    Environment.NewLine,
    // on each line, we'll render key: {list}, using string.Join again to create a nice
    // string for the list value
    diction.Select(kvp => kvp.Key + ": " + string.Join(", ", kvp.Value)
);
Console.WriteLine(result);

通常,要循环浏览字典的值,您可以像任何iEnumerable数据结构一样使用foreach或linq。Idictionary是一个iEnumerable>,因此foreach变量将是类型的KeyValuePair。

语法词语[键]允许您获取或设置存储在索引键的字典的值。这类似于数组[i]让您在索引i处获得或设置数组值的方式。例如:

var dict = new Dictionary<string, int>();
dict["a"] = 2;
Console.WriteLine(dict["a"]); // prints 2

如果您需要做的就是将每个字符串值的行存储,那么您使用的数据结构太复杂了。

这是一个基于Tuple类的简单示例:

public class Triplet : Tuple<string, string, string>
{
    public Triplet(string item1, string item2, string item3) : base(item1, item2, item3)
    {
    }
}

因此,您只需定义一个Triplet类,该类容纳3个字符串,就像上面一样。然后,您只需在代码中创建TripletsList

// Your code here
var data = new List<Triplet>();
// Add rows
data.Add(new Triplet("John", "Paul", "George"));
data.Add(new Triplet("Gene", "Paul", "Ace"));
// Display
foreach(Triplet row in data)
{
    Console.WriteLine("{0}, {1}, {2}", row.Item1, row.Item2, row.Item3);
}

这要简单地读取,理解和维护。

最新更新