Problem with list within Dictionary in C #

0

I have the following:

dic = new Dictionary<string, List<int>>;

But when I do dic.Add the values per parameter that I expect are a string and a List<int> , but for the same key ( string ) I want to add another int to the list, how Can I do it?

    
asked by Elpingui8 27.01.2017 в 05:18
source

2 answers

1

The problem is that when wanting to add a value of type int the list really what you are doing is add a new entry to the dictionary, therefore you mark the error of the key duplicated in the dictionary, for add a value to the list, you must first find the key in the dictionary and then add the value to the list. Using Linq you can add values to the list in this way:

Dictionary<string, List<int>> dic = new Dictionary<string, List<int>>();

dic.Add("1", new List<int> { 1, 2, 3 });
dic.Add("2", new List<int> { 4, 5, 6 });
dic.Add("3", new List<int> { 7, 8, 9 });

dic.FirstOrDefault(t => t.Key == "1").Value.Add(10);
dic.FirstOrDefault(t => t.Key == "1").Value.Add(11);
dic.FirstOrDefault(t => t.Key == "1").Value.Add(12);

foreach(var item in dic){
    Console.WriteLine("Llave string: " + item.Key);

    foreach (var valuesList in item.Value)
    {
        Console.WriteLine("Valores en lista: " + valuesList.ToString());
    }
}

Demo

    
answered by 27.01.2017 / 05:43
source
0

You can either use LINQ as Flxtr exposed above, or create a class that allows you to do it in a simple way:

class Program
{
    static void Main(string[] args)
    {
        Custom myCustom = new Custom(); //Instancias tu propio dic

        myCustom.Add("Hola", 10); //Agregas de a uno
        myCustom.Add("Hola", 30, 50, 10); //O agregas de a muchos

        var values = myCustom.Dic["Hola"]; //Casual, accediento a tus valores...
    }
}

public class Custom
{
    public Dictionary<string, List<int>> Dic { get; set; } = new Dictionary<string, List<int>>();

    public void Add(string str, params int[] pms)
    {
        if (Dic.Count > 0)
            if (!Dic.ContainsKey(str))
                Dic.Add(str, pms.ToList());
            else
            {
                var temp = Dic[str];

                Dic.Remove(str);
                Dic.Add(str, temp.Concat(pms).ToList());
            }
        else Dic.Add(str, pms.ToList());
    }
}
    
answered by 27.01.2017 в 09:00