Should I have a hash twice in C #?

I have code like the following:

class MyClass
{
    string Name;
    int NewInfo;
}

List<MyClass> newInfo = .... // initialize list with some values
Dictionary<string, int> myDict = .... // initialize dictionary with some values

foreach(var item in newInfo)
{
    if(myDict.ContainsKey(item.Name)) // 'A' I hash the first time here
         myDict[item.Name] += item.NewInfo // 'B' I hash the second (and third?) time here
    else
        myDict.Add(item.Name, item.NewInfo);
}

Is there a way to avoid performing two searches in the dictionary - the first time to see if the record contains, and the second time to update the value? Line โ€œBโ€ can even have two hash searches - one to get the int value, and the other to update it.

+5
source share
2 answers

Yes - use Dictionary.TryGetValue. To get the value, it takes a parameter outand returns the value of the found value. Here is your corrected code:

foreach(var item in newInfo)
{
    int value;
    if (myDict.TryGetValue(item.Name, out value))
    {
        myDict[item.Name] = value + item.NewInfo;
    }
    else
    {
        myDict[item.Name] = item.NewInfo;
    }
}

, . , out 0. item.NewInfo, item.NewInfo + value, . :

foreach(var item in newInfo)
{
    int value;
    myDict.TryGetValue(item.Name, out value);
    myDict[item.Name] = value + item.NewInfo;
}

- , .

, GetValueOrDefault, . , :

public static TValue GetValueOrDefault<TKey, TValue>
    (this IDictionary<TKey, TValue> dictionary, TKey key)
{
    TValue value;
    dictionary.TryGetValue(key, out value);
    return value;
}

public static TValue GetValueOrDefault<TKey, TValue>
    (this IDictionary<TKey, TValue> dictionary, TKey key,
     TValue customDefault)
{
    TValue value;
    if (dictionary.TryGetValue(key, out value))
    {
        return value;
    }
    else
    {
        return customDefault;
    }
}

:

foreach(var item in newInfo)
{
    myDict[item.Name] = myDict.GetValueOrDefault(item.Name) + item.NewInfo;
}

( GetValueOrDefault(item.Name, 0) .)

...

, - /. , TValue - , . , .

- ContainsKey, ( ) . , +=:

myDict[item.Name] = myDict[item.Name] + item.NewInfo;

(item.Name , , .)

Dictionary, " " , ,

bool Update(TKey key, Func<TValue, bool, TValue> replacementFunction)

replacementFunction , ( TValue, ) , , , . , . ( .)

+14

, . , , int.

class Program
{
    static void Main(string[] args)
    {
        var newInfo = new List<MyClass>();
        var myDict = new Dictionary<string, MyClass>();

        foreach (var item in newInfo)
        {
            MyClass temp;
            if (!myDict.TryGetValue(item.Name, out temp))
            {
                temp = new MyClass() { Name = item.Name };
                myDict.Add(temp.Name,temp);
            }

            temp.NewInfo += 1;

        }

    }
}


class MyClass
{
    public string Name;
    public int NewInfo;
}
+1

All Articles