2013-02-20 41 views
9

我試圖將值放入依賴於鍵的字典中......例如,如果在索引0的鍵列表中有字母「a」。我想將索引0的val添加到字典中的關鍵字「a」(字典(鍵是「a」在索引0,val在索引0)...字典(鍵是「b」在指數2,VAL在索引2))將項添加到字典中的列表

我期待像這樣的輸出:

在列表視圖LV1:1,2,4在列表視圖LV2:3,5

我「M得到的是在這兩個列表視圖3,4,5-

List<string> key = new List<string>(); 
List<long> val = new List<long>(); 
List<long> tempList = new List<long>(); 
Dictionary<string, List<long>> testList = new Dictionary<string, List<long>>(); 

key.Add("a"); 
key.Add("a"); 
key.Add("b"); 
key.Add("a"); 
key.Add("b"); 
val.Add(1); 
val.Add(2); 
val.Add(3); 
val.Add(4); 
val.Add(5);  

for (int index = 0; index < 5; index++) 
{ 

    if (testList.ContainsKey(key[index])) 
    { 
     testList[key[index]].Add(val[index]); 
    } 
    else 
    { 
     tempList.Clear(); 
     tempList.Add(val[index]); 
     testList.Add(key[index], tempList); 
    } 
}  
lv1.ItemsSource = testList["a"]; 
lv2.ItemsSource = testList["b"]; 

解決方案:

替換爲其他代碼部分:

testList.Add(鍵[指數],新的列表{VAL [指數]});

THX大家對你的幫助=)

+0

IM添加一個關鍵,只有當它不存在...如果(testList.ContainsKey(鍵[指數]) ).... – user2093348 2013-02-20 23:25:07

+0

當你得到鍵[3]時,你清除了'tempList',因爲「b」不在testList中。所以你最終得到了包含{3,4,5}的'tempList';字典中兩個元素的值都是對同一對象的引用。 – sigil 2013-02-20 23:30:22

回答

9

您正在使用的字典

for (int index = 0; index < 5; index++) 
    { 
     if (testList.ContainsKey(key[index])) 
     { 
      testList[k].Add(val[index]); 
     } 
     else 
     { 
      testList.Add(key[index], new List<long>{val[index]}); 
     } 
    } 

兩個鍵相同的列表只需創建一個新的列表(長),當該鍵不存在,那麼添加對它的長期價值

+0

thx非常...這解決了它=) – user2093348 2013-02-20 23:33:23

1

聽起來像一個家庭作業問題,但

for (int index = 0; index < 5; index++) 
{ 
    if (!testList.ContainsKey(key[index])) 
     testList.Add(key[index], new List<string> {value[index]}); 
    else 
     testList[key[index]].Add(value[index]); 
} 

this(以及其他相關的教程)

+1

你確定這會起作用嗎?如果在字典中不存在具有'key [index]'的項目,'testList [key [index]]'將變爲'null',導致'NullReferenceException'。 – 2013-02-20 23:27:18

+0

是啊沒有讀它,修改它。 – 2013-02-20 23:29:16

1

更換其他同:

else 
{ 
    tempList.Clear(); 
    tempList.Add(val[index]); 
    testList.Add(key[index], new List<long>(tempList)); 
} 

問題是,您正在添加對TempList的引用來這兩個鍵,它是相同的引用,所以它在第一個被替換。

我創建一個新的列表,所以它不會取代:new List<long>(tempList)

1

擺脫tempList的,取而代之的else條款:

testList.Add(key[index], new List<long> { val[index] }); 

,不使用ContainsTryGetValue要好得多:

for (int index = 0; index < 5; index++) 
{ 
    int k = key[index]; 
    int v = val[index]; 
    List<long> items; 
    if (testList.TryGetValue(k, out items)) 
    { 
     items.Add(v); 
    } 
    else 
    { 
     testList.Add(k, new List<long> { v }); 
    } 
} 
0

我不完全確定你要在這裏做什麼,但我保證你不想在每個字典條目中都有相同的列表。

templist是你的問題交換templist.Clear()templist = new List<Long>()

或去

for (int index = 0; index < 5; index++) 
{ 
if (!testList.ContainsKey(key[Index])) 
{ 
testList.Add(key[Index], new List<Long>()); 
} 
testList[key[index]].Add(val[index]); 
}