2012-11-28 123 views
5

我想要建立一个列表字典,但我正在阅读一个字符串,并需要使列表名称的字符串,并将它们添加到字典作为一个关键。列表字典

IE阅读“你好”

创建什么在

List<string> (insert read string here) = new List<string>(); 

读取然后添加列出名称为重点,以一个字典列表。

Dictionary.Add(readstring, thatlist); 

所有我能找到的是一个硬编码实现了这一点。

Turing.Add("S", S); 

我的目标:建立一个通用图灵机,所以我从一个文本文件,下一步,看起来像这样的输入读取,(Q0一) - > Q1 X R.

然后使用我读入的所有步骤以虚拟磁带“tape = XXYYZZBB”结束最终状态。

我有为此编写的伪代码,但我无法让字典正常工作。

编辑: 添加一些更多的信息,以减少混淆。 我给出了文本文件前两行的开始和结束状态。然后即时给予转换。

Q0 //启动状态 Q5 //端状态 Q0 Q1一个XR //过渡

伊夫剥离输入的前两行给我0和5然后已经创建了一个for循环来创建每个州的名单。

for (int i = 0; i <= endState; i++) 
{ 
List<string> i = new List<string>(); 
} 

然后我想添加每个列表名称作为我创建的列表字典的关键字。

Dictionary.Add(listname, thatlist); 

我需要帮助实现上面的代码,因为它给出错误。

+4

这很难理解你的要求。 –

+0

我已更新我的问题。谢谢您的帮助。 – MechaMan

回答

7

不要紧,你是否创建列表,

List<string> insertReadStringHere = new List<string>(); 

List<string> foo = new List<string>(); 

甚至

List<string> shellBeComingRoundTheMountain = new List<string>(); 

最重要的是,一旦你做了

MyDictionary.Add(theInputString, shellBeComingRoundTheMountain); 

可以然后通过

MyDictionary[theInputString] 

访问特定列表wherether最初的名单“被称为” insertReadStringHerefooshellBeComingRoundTheMountain

你甚至不需要在这样的命名变量中保存列表。例如,

Console.WriteLine("Input a string to create a list:"); 
var createListName = Console.ReadLine(); 
// As long as they haven't used the string before... 
MyDictionary.Add(createListName, new List<string>()); 

Console.WriteLine("Input a string to retrieve a list:"); 
var retrieveListName = Console.ReadLine(); 
// As long as they input the same string... 
List<string> retrievedList = MyDictionary[retrieveListName]; 

编辑:如果你想一定数目的列表,使用dictionarym apping从INT串,不串来串:

int maxNumberOfLists = 5; // or whatever you read from your text file. 
Dictionary<int, List<string>> myLists = 
      new Dictionary<int, List<string>> (maxNumberOfLists); 
for (int i = 1; i <= maxNumberOfLists; i++) 
    myLists[i] = new List<string>(); 

然后你就可以访问你的列表例如

var firstList = myLists[1]; 

通常我会推荐一个数组,但这会给你列表从1到5而不是从0到4,它似乎就是你想要的。

+0

所以我试图创建每个数值的列表1,2,... n在哪里我正在阅读的文本文件给我的最大状态,我会有。所以说,文本文件有5个最大状态,我想为每个数字1,2,3,...等创建一个列表。 for(int i = 0; i <= endState; i ++) { List i = new List (); } – MechaMan

+0

@MechaMan如果您想通过编号访问您的列表,我已经添加了一些代码。 – Rawling

+0

它工作了!非常感谢你的帮助。 – MechaMan