Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add items to a Dictionary<int, List<int>>

So I am looping through some objects and initializing a Dictionary> object.

So first I check if the key exists, if it does I will add to the List

If it doesn't, I will create a new key and new List

Is that the right logic?
I will have to do a:

new List<int>();

the first time I insert an item right?

i.e.:

if(myDic.ContainsKey(car.ID))
{
      myDic[car.ID].Add(car.MfgID);
}
else
{
   myDic.Add(car.ID, new List<int>);
   myDic[car.ID].Add(car.MfgID);
}
like image 632
mrblah Avatar asked Oct 28 '09 21:10

mrblah


1 Answers

Your approach works fine. It's a little inefficient as it requires two dictionary lookups (one for Contains and one for adding the item to the list). You can do it more efficiently using Dictionary.TryGetValue method:

List<int> list;
if (!myDic.TryGetValue(car.ID, out list))
    myDic.Add(car.ID, list = new List<int>());
list.Add(car.MfgId);

It's more efficient to fill the list and add it to the dictionary in one go (if it's possible in your case, of course). In C# 3.0, there's a feature called collection initializers that makes it easy to fill a list if items are known at compile time:

var list = new List<int> { 1, 9, 8, 9, 1, 8, 1, 2 }; 

You might also consider using something like this to map a key to multiple values.

like image 162
mmx Avatar answered Sep 22 '22 16:09

mmx