2014-01-27 151 views
0

詞典<字符串,列表<KeyValuePair <字符串,我已經創建的字符串>>>

Dictionary<string, List <KeyValuePair<string,string>>> diction = new Dictionary<string, List<KeyValuePair<string,string>>>(); 

後來我添加到列表:

diction.Add(firststring, new List<KeyValuePair<string,string>>()); 
diction[firststring].Add(new KeyValuePair<string, string>(1ststringlist, 2ndstringlist)); 

所以,現在,如果我想閱讀並在屏幕上顯示這本詞典,我將如何與foreach循環做到這一點?這就像3 dimmension語法,現在不是如何創建它並訪問它。

也可以解釋如何閱讀這部分?

diction[firststring].Add 

這是什麼意思?我在那裏讀全字典嗎?

謝謝你的回答和你的時間。

+0

這就是你想要做的嗎?將'(string,string,string)'三元組添加到它並顯示它們?還是有理由使用這種複雜的結構? –

+0

@RoyDictus同意......不知道你想做什麼,我們可以提供一個如下的答案,但如果你提供更多的信息,可能有更好的方法來實現你的目標。 –

+0

沒辦法,以前沒有回答... –

回答

5

字典商店key/value對。在你的情況,你的密鑰類型是string和價值類型爲List <KeyValuePair<string,string>>。所以當你做:

diction[firststring] 

firststring是你Key和您試圖訪問一個List <KeyValuePair<string,string>>。您的最佳選擇是嵌套循環我think.if你想顯示所有的值。例如:

foreach(var key in dict.Keys) 
{ 
    // dict[key] returns List <KeyValuePair<string,string>> 
    foreach(var value in dict[key]) 
    { 
     // here type of value is KeyValuePair<string,string> 

     var currentValue = value.Value; 
     var currentKey = value.Key; 

    } 
} 
+0

感謝隊友,我認爲它完成了這項工作。但是它並沒有顯示任何數據,但在我的程序中可能有些錯誤。 – Jan

2

有關打印數據結構,試試這個:

// string.Join(separator, enumerable) concatenates the enumerable together with 
// the separator string 
var result = string.Join(
    Environment.NewLine, 
    // on each line, we'll render key: {list}, using string.Join again to create a nice 
    // string for the list value 
    diction.Select(kvp => kvp.Key + ": " + string.Join(", ", kvp.Value) 
); 
Console.WriteLine(result); 

一般情況下,遍歷字典的值,可以使用的foreach或LINQ就像任何IEnumerable的數據結構。 IDictionary是一個IEnumerable>,所以foreach變量的類型是KeyValuePair。

語法diction [key]允許您獲取或設置存儲在索引鍵處的字典的值。這與array [i]如何讓您在索引i處獲取或設置數組值相似。例如:

var dict = new Dictionary<string, int>(); 
dict["a"] = 2; 
Console.WriteLine(dict["a"]); // prints 2 
0

如果您只需要存儲每行3個字符串值的行,那麼您使用的數據結構就太複雜了。

這裏有一個非常簡單的例子,基於該Tuple類:

public class Triplet : Tuple<string, string, string> 
{ 
    public Triplet(string item1, string item2, string item3) : base(item1, item2, item3) 
    { 
    } 
} 

所以你就定義一個類Triplet保存3串,像上面。然後,你只需在你的代碼中創建的Triplets一個List

// Your code here 
var data = new List<Triplet>(); 

// Add rows 
data.Add(new Triplet("John", "Paul", "George")); 
data.Add(new Triplet("Gene", "Paul", "Ace")); 

// Display 
foreach(Triplet row in data) 
{ 
    Console.WriteLine("{0}, {1}, {2}", row.Item1, row.Item2, row.Item3); 
} 

,這是更簡單閱讀,理解和維護。

+0

嗨,我需要這個公式,因爲我讀了3列的excel文件,將該列的每一行分配給這本字典,我只是想通過在屏幕上顯示它來檢查它是否正確。我無法使用靜態方法,因爲您的行數和內容是隨機的......稍後我需要隨機化第3列中的行順序並將其導出到文本文件。 – Jan

相關問題