我正在尝试将值放入依赖于键的字典中...例如,如果在索引0处的键列表中有一个字母"a".我想将索引为0的val添加到字典内的一个列表中,其中键为"a"(字典(键在索引0处为"a",在索引处为0处为val)...字典(键为"b"处于索引2,索引2处的val))
我期待这样的输出:
在listview lv1:1,2,4 in listview lv2:3,5
我得到的是两个列表视图中的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"];
Run Code Online (Sandbox Code Playgroud)
解:
将else代码部分替换为:
testList.Add(key [index],new List {val [index]});
大家帮忙=)