16

我正在尝试将值放入依赖于键的字典中......例如,如果在索引 0 处的键列表中有一个字母“a”。我想将索引为 0 的 val 添加到具有键“a”的字典内的列表中(字典(键为索引 0 处的“a”,索引 0 处的 val)...字典(键为“b”索引 2 ,索引 2)) 处的值

我期待这样的输出:

在列表视图 lv1:1,2,4 在列表视图 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"];

解决方案:

将 else 代码部分替换为:

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

谢谢大家的帮助=)

4

5 回答 5

24

您对字典中的两个键使用相同的列表

    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]});
        }
    }

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

于 2013-02-20T23:28:52.430 回答
3

摆脱tempList并替换您的else条款:

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

并且不要使用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 });
    }
}
于 2013-02-20T23:28:44.080 回答
1

替换为:

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

问题是,您正在向两个键添加对 TempList 的引用,它是相同的引用,因此它在第一个中被替换。

我正在创建一个新列表,因此它不会被替换:new List<long>(tempList)

于 2013-02-20T23:27:11.527 回答
0

听起来像一个家庭作业问题,但是

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]);
}

阅读本文(以及其他相关教程)

于 2013-02-20T23:25:23.840 回答
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]);
}
于 2013-02-20T23:31:09.817 回答