向字典中的列表添加项目

20

我正在尝试根据键将值放入字典中...例如,如果在键的列表中索引为0的位置有一个字母"a",我想将索引为0的val添加到字典内具有键"a"的列表中(字典(键为"a",索引为0,val为索引为0)...字典(键为"b",索引为2,val为索引为2))。

我期望得到这样的输出:

在listview lv1中:1、2、4,在listview lv2中:3、5

我得到的是在两个listview中都是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] });

感谢大家的帮助 =)


我只在键不存在的情况下添加它... 如果(testList.ContainsKey(key[index]))... - user2093348
当你到达key [3]时,清除tempList,因为“b”尚未在testList中。 因此,您最终得到包含{3,4,5}的tempList;字典中两个元素的值都是对同一对象的引用。 - sigil
5个回答

28

你在字典中使用了相同的列表键

    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),然后将长整型值添加到其中。


6
摆脱 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 });
    }
}

1

将else替换为:

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

问题在于,您将TempList的引用添加到了两个键中,这是相同的引用,因此在第一个键中被替换。
我正在创建一个新列表,以便它不会被替换:new List<long>(tempList)

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

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


1
你确定那会起作用吗?如果字典中不存在带有“key[index]”的项,则“testList[key[index]]”将为“null”,导致“NullReferenceException”。 - Jim Mischel

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接