C#列表<>添加名单字典 [英] C# List<> Add lists to dictionary

查看:135
本文介绍了C#列表<>添加名单字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

        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]);
}



甚至更好,如果 literere 实际上是一堆表达式可以内嵌指定,你可以做整个事情的集合初始化:

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:

Dictionary<string, List<Piese>> SetPiese = new Dictionary<string, List<Piese>>
{
    { "first-key", GenerareSetLitere("A", 1, 11) },
    { "second-key", GenerareSetLitere("B", 9, 2) }
};



等。

etc.

这篇关于C#列表&LT;&GT;添加名单字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆