Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In-line TryGetValue in If conditon and evaluate it's Value

Tags:

c#

dictionary

Is there any way how to write TryGetValue on one line in If condition. Normal way of calling TryGetValue would be:

string value;
Dictionary.TryGetValue("Key", out value);
If(value == "condition") { ... }

What I am looking for would be something like this.

If(Dictionary.TryGetValue("Key", out string) == "Condition") { ... }

I know that line wouldn't work, however it shows what is desired result.

Is there any way how to achieve this?

like image 810
Kamil Folwarczny Avatar asked Sep 17 '18 07:09

Kamil Folwarczny


1 Answers

You need to use the returned bool first but then you can use the out parameter(with >= C# 7):

if (Dictionary.TryGetValue("Key", out string value) && value == "Condition")
{
    //...
}

MSDN:

Starting with C# 7.0, you can declare the out variable in the argument list of the method call, rather than in a separate variable declaration.

If you're not using C#7 or you want it even shorter you could use this extension:

public static bool TryEvaluateValue<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key, Func<TValue, bool> evalValue)
{
    TValue val;
    if(!dict.TryGetValue(key, out val))
        return false;
    return evalValue(val);
}

Then your if-condition becomes:

if (Dictionary.TryEvaluateValue("Key", value => value == "Condition"))
{
    //...
}
like image 162
Tim Schmelter Avatar answered Nov 14 '22 21:11

Tim Schmelter