enforge
enforge

Reputation: 925

Better way to Code Dictionary Lookup?

Probably a very simple issue, but in writing some code where I have a mapping dictionary, I found that handling nulls and such has made my code look disgusting. Is there a better way to do this?

int brokerId = 0; // set a default value in case nothing is found
if(myTrade.Counterparty!=null) // dont bother if counterparty is null
  if (resolutionMap.Result["Broker"].ContainsKey((myTrade.Counterparty)))
    if (resolutionMap.Result["Broker"][myTrade.Counterparty] != null)
      primeBrokerId = Convert.ToInt32(resolutionMap.Result["Broker"][myTrade.Counterparty]);

Upvotes: 1

Views: 69

Answers (1)

row1
row1

Reputation: 5578

Store the value of resolutionMap.Result["Broker"] into a variable rather than looking it up multiple times e.g. var broker = resolutionMap.Result["Broker"];.

Also use TryGetValue() instead of ContainsKey() e.g.

CounterParty counterParty;
if (broker.TryGetValue(myTrade.Counterparty, out counterParty) && counterParty != null) { ....

Upvotes: 3

Related Questions