繁体   English   中英

C# 如何打印列表中的所有元素<dictionary<string,string> > 在控制台上? </dictionary<string,string>

[英]C# How can I print all elements from List<Dictionary<string,string>> on the console?

我是编程新手,在理解如何从列表中打印元素时遇到问题。 在给我的任务中,我收到:

List<Dictionary<string,string>>() list = new 
List<Dictionary<string,string>>(); 
list.Add(processString(string, string));
list.Add(processString(string, string));

processStrig 是一个Dictionary<string,string>并且两条记录的键相同。

我试图创建一个新的Dictionary ,然后用foreach填充它:

    Dictionary<string,string>() dict = new Dictionary<string, string>();
    foreach (Dictionary<string,string>r in list)
    {
        foreach (string inner in r.Keys)
        {
            if (!dict.ContainsKey(inner))
            {
                dict.Add(inner, r[inner]);
            }
        }
    } 

    

然后用另一个foreach打印新的字典,但它只显示第一个输入,因为键是相同的。 所以基本上我的问题是如何打印两个输入? output 应如下所示:

output 应如下所示:

[0]
"count":"some string"
"order":"some string"
[1]
"count":"some other string"
"order":"some other string"

如果您正在寻找循环解决方案,您可以尝试这样的事情:

 List<Dictionary<string, string>> list = ...

 for (int i = 0; i < list.Count; ++i) { 
   Console.WriteLine($"[{i}]");

   if (list[i] == null)
     Console.WriteLine("[null]");
   else 
     foreach (var pair in list[i])
       Console.WriteLine($"\"{pair.Key}\" : \"{pair.Value}\"");  
}
 

让我们有一个让你成为字典的方法:

public static Dictionary<string, string> MakeMeADictionary(string value1, string value2){
  var d = new Dictionary<string, string>();
  d["key1"] = value1;
  d["key2"] = value2;
  return d;
}

让我们调用它两次,将结果添加到列表中:

var listOfDicts = new List<Dictionary<string, string>>();

listOfDicts.Add(MakeMeADictionary("first val", "second val"));
listOfDicts.Add(MakeMeADictionary("third val", "fourth val"));

让我们枚举列表,然后枚举其中的每个字典:

foreach(var dict in listOfDicts){

  Console.WriteLine("Enumerating a dictionary");

  foreach(var keyValuePair in dict)
    Console.WriteLine($"Key is: {keyValuePair.Key}, Value is: {keyValuePair.Value}");

}

结果:

Enumerating a dictionary
Key is: key1, Value is: first val
Key is: key2, Value is: second val
Enumerating a dictionary
Key is: key1, Value is: third val
Key is: key2, Value is: fourth val

争取使您的代码有意义的变量名称; List<Person>的复数或集合类型的名称,foreach vars people被枚举的复数有意义等。有foreach(var person in people) ..我无法理解你在foreach(var r in list)中选择r

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM