0

我是 C-sharp 的新手。在避免不安全代码的同时尝试解决以下问题。对不起,如果我的描述似乎过分;只是想尽可能清楚。

我正在阅读具有以下格式的文件:

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

我正在尝试创建一个数据结构,以便“column1”中的每个唯一项目都链接到 { column2 , column3} 对。像这样的东西:

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

这里的问题是您事先不知道“column1”将有多少不同的独特项目。到目前为止,我已经提前创建了 listdictionary 变量,这样我就可以“.add()”这些对了。如果我在 C++ 中执行此操作,我会有某种数组保存指向包含 {column2, column 3} 对的结构的指针。我承认这可能不是最好的解决方案,但这是我遵循的思路C#。

简而言之,我正在寻求有关如何动态创建 listdictionary 的建议,或者是否有更好的方法来解决该问题。

4

3 回答 3

1

假设您在数组上有行内容,您可以使用以下内容:

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

问候

于 2012-07-26T23:57:56.223 回答
0

如果您已经将数组加载到内存中,则可以使用 LINQ ToLookup 方法:

overallArray.ToLookup(x => x.Column1, x => new{x.Column2, x.Column3});
于 2012-07-27T00:14:02.573 回答
0
foreach (DictionaryEntry de in myListDictionary)
{
    //...
}

我为您做了一些研究,并提出了这篇代码文章。看看这个。

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

于 2012-07-27T00:21:23.247 回答