Kamil Folwarczny
Kamil Folwarczny

Reputation: 591

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

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?

Upvotes: 10

Views: 13351

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460098

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"))
{
    //...
}

Upvotes: 15

Related Questions