user1556247
user1556247

Reputation: 3

C# dynamic list dictionary

I'm new to C-sharp. Trying to approach the following issue while avoiding unsafe code. Sorry if my description seems excessive; just trying to be as clear as possible.

I'm reading a file that has the following format:

Column1  Column2 Column3
1          a        q
1          a        w
2          a        b
1          e        v
3          w        q
3          q        x
...        ...      ...

I'm trying to create a data structure such that every unique item in "column1" is linked to a{ column2 , column3} pair. Something like this:

{1} => {a, q}, {a,w} , {e,v}
{2} => {a,b}
{3} => {w,q} , {q,x}

The issue here is that you don't know in advance how many different unique items "column1" will have. So far, I have dealt by creating listdictionary variables in advance so that I can just ".add()" the pairs. If I were doing this in C++, I would have some kind of array holding pointers to a structure holding {column2, column 3} pairs.I admit this might not be the best solutions, but it is the line of thought I was following in C#.

In short, I'm asking for suggestions on how to dynamically create a listdictionary , or if there is a better way to approach the problem.

Upvotes: 0

Views: 1844

Answers (3)

LOZ
LOZ

Reputation: 1177

foreach (DictionaryEntry de in myListDictionary)
{
    //...
}

I did some research for you, and came up with this code article. check it out.

http://msdn.microsoft.com/en-us/library/system.collections.specialized.listdictionary.aspx

Upvotes: 0

Tevin
Tevin

Reputation: 1404

If you have the array loaded into memory already, you could use the LINQ ToLookup method:

overallArray.ToLookup(x => x.Column1, x => new{x.Column2, x.Column3});

Upvotes: 0

Andre Calil
Andre Calil

Reputation: 7692

Assuming that you have the line content on a array, you can work with something like this:

        Dictionary<string, List<string[]>> allPairs = new Dictionary<string, List<string[]>>();

        foreach (string currentLine in allLines)
        {
            string[] lineContent = currentLine.Split(" "); //or something like it. Maybe it should be a TAB
            string[] newPair = new string[2];
            newPair[0] = lineContent[1];
            newPair[1] = lineContent[2];

            if (allPairs[lineContent[0]] == null)
            {
                allPairs[lineContent[0]] = new List<string[]>();
            }

            allPairs[lineContent[0]].Add(newPair);
        }

Regards

Upvotes: 1

Related Questions