Pulling a subset of elements from a Dictionary

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;
}


1 Answer

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]);
}

• This is exactly what I was hoping for. Feb 25 '11 at 17:10
• you probably meant yield return resourceNames.. Feb 21 '19 at 22:32