2016-03-04 58 views
2

我是新來的C#,我試圖定義一個詞典有:

填充具有嵌套列表值的詞典的正確語法是什麼?

關鍵:

字符串


爲值:

字符串列表的列表。


我能想出了(?不能完全肯定它是正確的)是這樣的:

var peopleWithManyAddresses = new Dictionary<string, List<List<string>>> {}; 


現在,如果上面是正確的,我想知道如何以填充一個項目的peopleWithManyAddresses

智能感知告訴我,以下是正確的只有直到「盧卡斯」:

peopleWithManyAddresses.Add("Lucas", { {"first", "address"}, {"second", "address"} }); 

什麼是它的正確語法?

P.S.我知道我可以使用一堂課,但爲了學習的目的,我想現在就這樣做。

回答

4

要初始化List<List<string>>對象,必須使用new List<List<string>> { ... }語法。要初始化每個子列表,您必須使用類似的語法,即new List<string> {... }。以下是一個示例:

var peopleWithManyAddresses = new Dictionary<string, List<List<string>>>(); 

peopleWithManyAddresses.Add("Lucas", new List<List<string>> 
{ 
    new List<string> { "first", "address" }, 
    new List<string> { "second", "address" } 
}); 
3

您的初始化語句是正確的。

使用C#6。0,你可以使用下面的語法來填充一個項目:

var dict = new Dictionary<string, List<List<string>>> 
{ 
    ["Lucas"] = new[] 
    { 
     new[] { "first", "address" }.ToList(), 
     new[] { "second", "address" }.ToList(), 
    }.ToList() 
}; 

您可以使用下面的填充兩項:

var dict = new Dictionary<string, List<List<string>>> 
{ 
    ["Lucas"] = new[] 
    { 
     new[] { "first", "address" }.ToList(), 
     new[] { "second", "address" }.ToList(), 
    }.ToList(), 
    ["Dan"] = new[] 
    { 
     new[] { "third", "phone" }.ToList(), 
     new[] { "fourth", "phene" }.ToList(), 
    }.ToList(), 
}; 

如果你想在以後添加更多的數據,你可以做以下:

dict["Bob"] = new[] 
{ 
    new[] { "fifth", "mailing" }.ToList(), 
    new[] { "sixth", "mailing" }.ToList(), 
}.ToList(); 
+0

謝謝。是'new [] {「apples」,「oranges」,...} ToList()'基本上是一個數組被轉換爲列表?我想知道這是否會影響性能? –

+1

是的,這只是填充列表的一種方式,讓編譯器找出列表的類型爲'string'。它不應該影響性能。 – devuxer

+2

@jj_ - 影響微乎其微。 '.ToList()'重載使用'Array.CopyTo'調用來複制元素,這非常快。實際上,當有很多元素被初始化時,新列表(){「A」,「B」}'語法可能會變慢,因爲它在引擎蓋下反覆調用'.Add'。我用這兩種方法進行了一次測試 - 將12個元素添加到列表中時,'.ToList()'方法的速度提高了大約10%。 – Enigmativity

1

第一I創建ListDictionary分隔:

List<string> someList = new List<string<(); 
var otherList = new List<List<string>>(); 
var peopleWithManyAddresses = new Dictionary<string, List<List<string>>> {}; 

首先在someList

字符串添加
someList.Add("first"); 
someList.Add("addresss"); 

然後加在otherList:

otherList.Add(someList); 

現在創建的字符串的新名單:

var thirdList = new List<string>(); 
thirdList.Add("second"); 
thirdList.Add("addresss"); 

並添加字符串的最後名單在其他列表中並添加字典

otherList.Add(thirdList); 
peopleWithManyAddresses.Add("Lucas", otherList); 
+0

非常感謝..把它切成小塊...... :)爲了學習更多關於c#語法的知識,我避免了這種方法,但在這裏仍然很好。 –