[英]C# dynamic list dictionary
I'm new to C-sharp. 我是C锋利的新手。 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. 我正在尝试创建一个数据结构,以使“ column1”中的每个唯一项都链接到一对{column2,column3}对。 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. 这里的问题是,您事先不知道“ column1”将有多少种不同的独特项。 So far, I have dealt by creating listdictionary variables in advance so that I can just ".add()" the pairs.
到目前为止,我已经预先创建了listdictionary变量,以便可以仅对“ .add()”进行处理。 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#.
如果我使用C ++进行此操作,我将拥有某种数组,其中包含指向包含{column2,column 3}对的结构的指针。我承认这可能不是最佳解决方案,但这是我遵循的思路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. 简而言之,我正在寻求有关如何动态创建listdictionary的建议,或者是否存在解决该问题的更好方法。
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 问候
如果已经将数组加载到内存中,则可以使用LINQ ToLookup方法:
overallArray.ToLookup(x => x.Column1, x => new{x.Column2, x.Column3});
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 http://msdn.microsoft.com/zh-CN/library/system.collections.specialized.listdictionary.aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.