Get a list of every value for a given key in a set of dictionaries?
How can I write this code more cleanly/concisely?
/// <summary>
/// Creates a set of valid URIs.
/// </summary>
/// <param开发者_如何学编程 name="levelVariantURIDicts">A collection of dictionaries of the form:
/// dict["filePath"] == theFilePath </param>
/// <returns></returns>
private ICollection<string> URIsOfDicts(ICollection<IDictionary<string, string>> levelVariantURIDicts)
{
ICollection<string> result = new HashSet<string>();
foreach (IDictionary<string, string> dict in levelVariantURIDicts)
{
result.Add(dict["filePath"]);
}
return result;
}
You can select dict["filePath"]
for each dict
in levelVariantURIDicts
with Select:
return levelVariantURIDicts.Select(dict => dict["filePath"])
.Distinct()
.ToList();
Drop .Distinct()
if duplicate entries in the result are fine.
Drop .ToList()
if you don't really need to return an ICollection<T> and an IEnumerable<T> is fine.
精彩评论