将项添加到字典中的列表

use*_*348 13 c# dictionary list

我正在尝试将值放入依赖于键的字典中...例如,如果在索引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]});

大家帮忙=)

Ste*_*eve 18

您在"词典"中对两个键使用相同的列表

    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]});
        }
    }
Run Code Online (Sandbox Code Playgroud)

只需在密钥不存在时创建一个新的List(Of Long),然后将long值添加到它


Jim*_*hel 6

删除tempList并将您的else条款替换为:

testList.Add(key[index], new List<long> { val[index] });
Run Code Online (Sandbox Code Playgroud)

并且不要使用Contains. TryGetValue好多了:

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 });
    }
}
Run Code Online (Sandbox Code Playgroud)