词典<字符串,列表>>
:词典<字符串,列表<KeyValuePair <字符串,我已经创建的字符串>>>
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
对。在你的情况,你的密钥类型是string
和价值类型为List <KeyValuePair<string,string>>
。所以当你做:
diction[firststring]
firststring
是你Key
和您试图访问一个List <KeyValuePair<string,string>>
。您的最佳选择是嵌套循环我think.if你想显示所有的值。例如:
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;
}
}
感谢队友,我认为它完成了这项工作。但是它并没有显示任何数据,但在我的程序中可能有些错误。 – Jan
有关打印数据结构,试试这个:
// 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);
一般情况下,遍历字典的值,可以使用的foreach或LINQ就像任何IEnumerable的数据结构。 IDictionary是一个IEnumerable>,所以foreach变量的类型是KeyValuePair。
语法diction [key]允许您获取或设置存储在索引键处的字典的值。这与array [i]如何让您在索引i处获取或设置数组值相似。例如:
var dict = new Dictionary<string, int>();
dict["a"] = 2;
Console.WriteLine(dict["a"]); // prints 2
如果您只需要存储每行3个字符串值的行,那么您使用的数据结构就太复杂了。
这里有一个非常简单的例子,基于该Tuple
类:
public class Triplet : Tuple<string, string, string>
{
public Triplet(string item1, string item2, string item3) : base(item1, item2, item3)
{
}
}
所以你就定义一个类Triplet
保存3串,像上面。然后,你只需在你的代码中创建的Triplets
一个List
:
// 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);
}
,这是更简单阅读,理解和维护。
嗨,我需要这个公式,因为我读了3列的excel文件,将该列的每一行分配给这本字典,我只是想通过在屏幕上显示它来检查它是否正确。我无法使用静态方法,因为您的行数和内容是随机的......稍后我需要随机化第3列中的行顺序并将其导出到文本文件。 – Jan
这就是你想要做的吗?将'(string,string,string)'三元组添加到它并显示它们?还是有理由使用这种复杂的结构? –
@RoyDictus同意......不知道你想做什么,我们可以提供一个如下的答案,但如果你提供更多的信息,可能有更好的方法来实现你的目标。 –
没办法,以前没有回答... –