我正在尝试遍历以下字典
这是字典的样子
B-> N, P
N -> B, S
S-> N
P -> X, Y, U, I, R
如何仅在P的密钥列表上进行迭代,以便它应返回X,Y,U,I,R?
Dictionary<string, List<string>> vertices = new Dictionary<string, List<string>>();
答案 0 :(得分:0)
您可以尝试
foreach (var item in vertices["P"])
{
//handle item value here
}
答案 1 :(得分:0)
尝试一下
Dictionary<string, List<string>> vertices = new Dictionary<string, List<string>>();
vertices.Add("B", new List<string> { "N", "P" });
vertices.Add("N", new List<string> { "B", "S" });
vertices.Add("S", new List<string> { "N" });
vertices.Add("P", new List<string> { "X", "Y", "U", "I", "R" });
vertices.TryGetValue("P", out List<string> value);
foreach (string s in value)
{
Console.Write(s + ",");
}
答案 2 :(得分:0)
因此,您的迭代应如下所示:
var result = vertices.SingleOrDefault(keyValuePair => keyValuePair.Key == "P");
List<string> list = result.Value;
list.ForEach(Console.WriteLine);
答案 3 :(得分:-1)
我将为此使用LINQ:
KeyValuePair<string, List<string>> entry = vertices.FirstOrDefault(s => s.Key == "P");
foreach(string whatever in entry.Value)
{
//your text is here
}