开发者

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:

开发者_StackOverflownew 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);
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜