我試圖將值放入依賴於鍵的字典中......例如,如果在索引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大家對你的幫助=)
IM添加一個關鍵,只有當它不存在...如果(testList.ContainsKey(鍵[指數]) ).... – user2093348 2013-02-20 23:25:07
當你得到鍵[3]時,你清除了'tempList',因爲「b」不在testList中。所以你最終得到了包含{3,4,5}的'tempList';字典中兩個元素的值都是對同一對象的引用。 – sigil 2013-02-20 23:30:22