문제

I'm writing a program that needs to use a Dictionary<TKey,groupimplementation<TValue>>for example what i use is Dictionary<TKey,List<TValue>>,every time I need to add items I need to initialize a list of type t if the key doesn't exist and if it does I only need to access the list and add the item.

*is this the most efficient way (in terms of speed) to do this ? or is there any other way ?

one more thing what is the time complexity for checking for the key using .ContainsKey()

by the way I can't use iLookup since it's immutable and the only way to initialize one is from the .tolookup()methode

도움이 되었습니까?

해결책

is this the most efficient way (in terms of speed) to do this ? or is there any other way ?

Before adding an item to the list you have to initialize it (if the list is not already initialized). Only looking at your description (not code) I can only guess that it is fine. For checking if the key exists, you are using ContainsKey which has the O(1) complexity.

what is the time complexity for checking for the key using .ContainsKey()

Dictionary<TKey, TValue>.ContainsKey Method - MSDN

This method approaches an O(1) operation.

다른 팁

The most efficient way to access and modify a dictionary's value is to use it's TryGetValue method.

So you only need to access it once instead of twice if you first check if it contains a given key.

For example:

List<TValue> theList;
if (dictionary.TryGetValue(theKey, out theList))
    theList.Add(newItem);
else
    dictionary.Add(theKey, new List<TValue> { newItem });
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top