Get a list of each value for a given key in a dictionary set?

How can I write this code more clearly / 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;
    }
+3
source share
1 answer

You can select dict["filePath"]for each dictin levelVariantURIDictsusing Select :

return levelVariantURIDicts.Select(dict => dict["filePath"])
                           .Distinct()
                           .ToList();

Drop .Distinct()if duplicate entries are accurate as a result.
Drop .ToList()if you really don't need to return ICollection <T> and IEnumerable <T> well.

+10
source

Source: https://habr.com/ru/post/1737588/


All Articles