繁体   English   中英

C#动态列表字典

[英]C# dynamic list dictionary

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

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

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的建议,或者是否存在解决该问题的更好方法。

假设您在一个数组中包含行内容,则可以使用以下内容:

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

问候

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

overallArray.ToLookup(x => x.Column1, x => new{x.Column2, x.Column3});
foreach (DictionaryEntry de in myListDictionary)
{
    //...
}

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

http://msdn.microsoft.com/zh-CN/library/system.collections.specialized.listdictionary.aspx

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM