0

Im trying to figure out to convert the following statement to a trygetvalue.

Any help would be greatly appreciated.

filters.ContainsKey("companyCode") ? filters["companyCode"] : string.Empty;

I have code that I inherited that has about 25 of these that builds one query statement.

jeffkenn
  • 201
  • 4
  • 16

2 Answers2

6

You have to create an if statement where you assign the default in case the filter wasn't found:

For C# 7:

if (!filters.TryGetValue("companyCode", out string value))
    value = string.Empty;

And pre-C# 7:

string value;

if (!filters.TryGetValue("companyCode", out value))
    value = string.Empty;
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
  • Thanks so much. I just couldn't see it. – jeffkenn Mar 20 '18 at 15:50
  • Why an `if` statement and not a ternary? – maccettura Mar 20 '18 at 15:51
  • Because for beginner programmers this code is clearer. Functionally it wouldn't matter which to pick @maccettura. – Patrick Hofman Mar 20 '18 at 15:52
  • @maccettura What code would be in the `true` block of a ternary operation where `TryGetValue` is the condition? Seems like a redundant assignment would have to happen. – Rufus L Mar 20 '18 at 16:05
  • 1
    @RufusL See Tim's answer: `string result = filters.TryGetValue("companyCode", out string code) ? code : string.Empty;` – maccettura Mar 20 '18 at 16:09
  • @maccettura Yeah, sorry, I meant why would that be better? You have an additional assignment operation in the `true` case. Just curious. – Rufus L Mar 20 '18 at 16:09
  • 1
    @RufusL I wouldnt say a ternary is better, I just personally thought it was cleaner. You have a solid point about the extra assignment though. – maccettura Mar 20 '18 at 16:11
4

With C#7 you can use this one liner:

string result = filters.TryGetValue("companyCode", out string code) ? code : string.Empty;

If you can't use inline out variables you need two lines:

string code;
string result = filters.TryGetValue("companyCode", out code) ? code : string.Empty;
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939