简体   繁体   中英

how to populate a list dynamically within a dictionary in c#?

i want to populate a list in dictionary.timeslot_events.Add(t, new List<int>() { i }); but it is giving me exception that more an item with the same key has already added.
i have also tried to populate list with add function timeslot_events.Add(t, new List<int>() { i }); but it is giving me exception that the given key was not present in the dictionary.

kindly guide how can i populate it successfully.? In C++, i used to do it with map<int, vector<int>>

for (int i = 0; i < data.noevents; i++)
{
    int t = (int)(rg.Next(1, 45));
    Console.WriteLine(t);
    timeslot_events.Add(t, new List<int>() { i });

}

Check if key is already present then add against that key else insert new KeyValue pair like below:

for (int i = 0; i < data.noevents; i++)
{
    int t = (int)(rg.Next(1, 45));
    Console.WriteLine(t);
    if (timeslot_events.ContainsKey(t))
    {
        if (timeslot_events[t] == null)
        {
            timeslot_events[t] = new List<int>();
        }
        timeslot_events[t].Add(i);
    }
    else
    {
        timeslot_events.Add(t, new List<int>() { i });
    }   

}

I would use a bit of LINQ.

var query = 
    from n in Enumerable.Range(0, data.noevents)
    group n by rg.Next(1, 45);

foreach (var x in query)
{
    timeslot_events.Add(x.Key, x.ToList());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM