user1679671
user1679671

Reputation:

How to find an element in Dictionary with LINQ

I have a code:

var status = ...
var StatusMapping = new Dictionary<AnotherStatus, IList<Status>>
{
    {
        AnotherStatus,
        new List<Status>
        {
            Status1,
            Status2
        }
    }
}

foreach (var keyValuePair in StatusMapping)
{
    if (keyValuePair.Value.Contains(status))
    {
        return keyValuePair.Key;
    }
}

throw Exception(); 

I'm new to C#, switched from Java. In java it is easily done like this:

return StatusMapping
    .entrySet()
    .stream()
    .filter(e -> e.getValue().contains(status))
    .map(Map.Entry::getKey)
    .findFirst()
    .orElseThrow(() -> new Exception());

Is there a way to do it with LINQ?

Upvotes: 2

Views: 432

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1499880

Firstly, if you're doing this regularly, you might want to consider an alternative data structure. Dictionaries aren't really intended for frequent "lookup based on some aspect of the value".

Oh it's rather simpler in C# :)

var key = StatusMapping.First(x => x.Value.Contains(status)).Key;

First() will throw an exception if there aren't any matches.

If you wanted to end up with a default value instead, you could use:

var key = StatusMapping.FirstOrDefault(x => x.Value.Contains(status)).Key;

This will result in key being the default value for AnotherStatus (or whatever the key type is).

Note that this only works exactly like this because KeyValuePair<,> is a value type, so the default value is non-null, with a default key. If you had a sequence of reference types, you would need something like:

var property = sequence.FirstOrDefault(whatever)?.Property;

... where ?. is the null conditional operator.

Upvotes: 10

Related Questions