HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Pulling a subset of elements from a Dictionary

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
pullingelementsdictionaryfromsubset

Problem

I have a function that returns a set of values from a Dictionary.

I don't currently want to allow it to throw KeyNotFoundException, so I'm filtering the keys out before I try to select the values.

I have a feeling this can be done in a more straightforward fashion, but I'm not sure where to go with it.

// this.resources is a Dictionary

public IEnumerable GetResources(IEnumerable resourceNames)
{
    HashSet hs = new HashSet(resourceNames);

    hs.IntersectWith(this.resources.Keys);

    List resources = new List();

    foreach(string resourceName in hs)
    {
        resources.Add(this.resources[resourceName]);
    }

    return resources;
}

Solution

I would write it the obvious straight-forward LINQ way, which gives you good readability as well as lazy evaluation:

public IEnumerable GetResources(IEnumerable resourceNames)
{
    return resourceNames
        .Where(name => resources.ContainsKey(name))
        .Select(name => resources[name]);
}

Code Snippets

public IEnumerable<Resource> GetResources(IEnumerable<string> resourceNames)
{
    return resourceNames
        .Where(name => resources.ContainsKey(name))
        .Select(name => resources[name]);
}

Context

StackExchange Code Review Q#993, answer score: 14

Revisions (0)

No revisions yet.