-1

I'm use to having a dictionary like the following

Dictionary<int, int> interestCountsDict = ( ...

and then, to get a value out of it that may or may not exist, have code like this

session.InterestCount = interestCountsDict.ContainsKey(session.Id)
                        ? interestCountsDict[session.Id]
                        : 0;

With all the improvements to C#, is there a better way to do this without having to call ContainsKey first?

Pete
  • 3,111
  • 6
  • 20
  • 43

2 Answers2

3

Since .NET Core 2.0 and .NET Standard 2.1, there is CollectionExtensions.GetValueOrDefault which does exactly what you need.

Zdeněk Jelínek
  • 2,611
  • 1
  • 17
  • 23
  • https://source.dot.net/#System.Collections/System/Collections/Generic/CollectionExtensions.cs,36e0c75545760030 –  Jun 20 '21 at 18:14
0

You can use TryGetValue which return the value for the key, if it exists, or it will return default(T), for the out parameter:

interestCountsDict.TryGetValue(session.Id, out var interestCount);
session.InterestCount = interestCount;

Per the comment, the class property can't be an out variable. Instead you can inline a new variable with out var interestCount then assign its value to your class property.

Matt U
  • 4,970
  • 9
  • 28
  • 2
    This is not legal if `session.InterestCount` is a property, which it likely is. An intermediate local temporary would still be needed, though it can be declared inline (`out int interestCount`). – Jeroen Mostert Jun 20 '21 at 17:47
  • Thanks for that, I obviously didn't think about that. I updated the answer. – Matt U Jun 20 '21 at 18:05