Cerzi
Cerzi

Reputation: 830

Simplifying TryGetValue to access an attribute of the key's value?

Is there any way to do this, such as using lambdas in some fashion? If I have a Dictionary, is it possible to shorten my code so that TryGetValue puts out Foo.a instead of just returning the object?

Right now it feels a bit long-winded, with eg "a" as int:

int a;
Foo bar;
if(!dict.TryGetValue(key, out valueObj)) {
    a = 0;
}
else {
    a = bar.a;
}

Upvotes: 1

Views: 1857

Answers (3)

Haytam
Haytam

Reputation: 4733

Here's a one liner:

int a = dict.TryGetValue(key, out SomeClass valueObj) ? valueObj.a : 0;

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726539

You can slightly simplify this with a conditional expression and the new C#'s out var feature:

int a = dict.TryGetValue(key, out var valueObj) ? valueObj.a : 0;

This is essentially the same solution as you presented, only rewritten on a single line.

Upvotes: 4

FaizanHussainRabbani
FaizanHussainRabbani

Reputation: 3439

Why you need LINQ to achieve something so simple?

public Object GetObjectFromDict(string foo)
{
    if (someDict.ContainsKey(foo))
    {
        return someDict[foo];
    }
    return null;
}

Upvotes: 2

Related Questions