如何更清洁/简洁地编写此代码?
/// <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;
}
答案 0 :(得分:10)
您可以使用Select为dict["filePath"]
中的每个dict
选择levelVariantURIDicts
:
return levelVariantURIDicts.Select(dict => dict["filePath"])
.Distinct()
.ToList();
如果结果中的重复条目正常,则删除.Distinct()
如果您确实不需要返回ICollection,请删除.ToList()
&lt; T&gt;和IEnumerable&lt; T&gt;很好。