Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding items to a list in a dictionary

I'm trying to put values into a dictionary dependent on the key... For example, if in a list of keys at the index 0 there is a letter "a". I want to add the val with index 0 to a list inside of a dictionary with the key "a" ( dictionary (key is "a" at index 0 , val at index 0) ... dictionary (key is "b" at index 2 , val at index 2))

I'm expecting an output like this:

in listview lv1: 1,2,4 in listview lv2: 3,5

what I'm getting is 3,4,5 in both listviews

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"];

Solution:

replace the else code section with :

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

thx everybody for your help =)

like image 430
user2093348 Avatar asked Feb 20 '13 23:02

user2093348


1 Answers

You are using the same list for both keys in the Dictionary

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

Just create one new List(Of Long) when the key doesn't exists then add the long value to it

like image 69
Steve Avatar answered Oct 11 '22 21:10

Steve