patterncsharpModerate
Pulling a subset of elements from a Dictionary
Viewed 0 times
pullingelementsdictionaryfromsubset
Problem
I have a function that returns a set of values from a
I don't currently want to allow it to throw
I have a feeling this can be done in a more straightforward fashion, but I'm not sure where to go with it.
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.