2012-11-28 70 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