[英]C# List<> Add lists to dictionary
Dictionary<string, List<Piese>> SetPiese = new Dictionary<string, List<Piese>>();
char[] litere = "ABCDEFGHIJLMNOPRSTUVXZ".ToCharArray();
for (int i = 1; i <= litere.Length; i++) {
SetPiese.Add(litere[i], Set + litere[i]);
}
List<Piese> SetA = GenerareSetLitere("A", 1, 11);
List<Piese> SetB = GenerareSetLitere("B", 9, 2);
List<Piese> SetC = GenerareSetLitere("C", 1, 5);
................................................
So I have many lists and I want to add them to a dictionary. 所以我有很多列表,我想将它们添加到字典中。 How can I do this right ?
我该怎么做呢?
Quite simply, don't declare them in separate variables to start with. 很简单,不要在单独的变量中声明它们。 That will always be a pain to work with programmatically.
以编程方式进行工作始终是一件痛苦的事情。 If you'd started with:
如果您开始使用:
List<Piese>[] sets = new List<Piese>[]
{
GenerareSetLitere("A", 1, 11),
GenerareSetLitere("B", 9, 2),
GenerareSetLitere("C", 1, 5)
...
};
then you could use: 那么您可以使用:
// Note loop condition change
for (int i = 0; i < litere.Length; i++) {
SetPiese.Add(litere[i], sets[i]);
}
Or even better, if literere
is actually a bunch of expressions you can specify inline, you could do the whole thing in a collection initializer: 甚至更好的是,如果
literere
实际上是一堆表达式,您可以指定内联,则可以在集合初始化程序中完成全部操作:
Dictionary<string, List<Piese>> SetPiese = new Dictionary<string, List<Piese>>
{
{ "first-key", GenerareSetLitere("A", 1, 11) },
{ "second-key", GenerareSetLitere("B", 9, 2) }
};
etc. 等等
I guess this works: 我猜这可行:
Dictionary<string, List<Piese>> SetPiese = new Dictionary<string, List<Piese>>();
List<Piese> SetA = GenerareSetLitere("A", 1, 11);
List<Piese> SetB = GenerareSetLitere("B", 9, 2);
List<Piese> SetC = GenerareSetLitere("C", 1, 5);
SetPiese.Add("A", SetA);
SetPiese.Add("B", SetB);
SetPiese.Add("C", SetC);
I'm not sure because you haven't mentioned the key of your dictionary. 我不确定,因为您没有提到字典的键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.