Tarida George
Tarida George

Reputation: 1303

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 ?

Upvotes: 0

Views: 31600

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1503290

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:

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

etc.

Upvotes: 7

Tim Schmelter
Tim Schmelter

Reputation: 460278

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.

Upvotes: 2

Related Questions