views:

161

answers:

1

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);
}
+7  A: 

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.

Mehrdad Afshari
Great, now you and Reed just need to combine both answers into one :)
Pavel Minaev
Oh, and collection initializers might also be worth mentioning.
Pavel Minaev
@Pavel: My answer eliminates the need for reordering mentioned in Reed's answer. It always does a single dictionary lookup.
Mehrdad Afshari