8
\$\begingroup\$

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<string, Resource>

public IEnumerable<Resource> GetResources(IEnumerable<string> resourceNames)
{
    HashSet<string> hs = new HashSet<string>(resourceNames);

    hs.IntersectWith(this.resources.Keys);

    List<Resource> resources = new List<Resource>();

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

    return resources;
}
\$\endgroup\$
0
14
\$\begingroup\$

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

public IEnumerable<Resource> GetResources(IEnumerable<string> resourceNames)
{
    return resourceNames
        .Where(name => resources.ContainsKey(name))
        .Select(name => resources[name]);
}
\$\endgroup\$
2
  • \$\begingroup\$ This is exactly what I was hoping for. \$\endgroup\$
    – mskfisher
    Feb 25 '11 at 17:10
  • \$\begingroup\$ you probably meant yield return resourceNames.. \$\endgroup\$ Feb 21 '19 at 22:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.