7

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);
}
mrblah
  • 93,893
  • 138
  • 301
  • 415

1 Answers1

23

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.

Community
  • 1
  • 1
mmx
  • 402,675
  • 87
  • 836
  • 780