2010-03-18 51 views
3

我該如何更清晰/簡潔地編寫此代碼?獲取一組詞典中給定鍵的每個值的列表?

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

回答

10

您可以Select選擇dict["filePath"]levelVariantURIDicts每個dict

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

下降.Distinct()如果結果重複條目都很好。
刪除.ToList()如果您確實不需要返回ICollection <T>和IEnumerable <T>很好。

+0

這是光榮的。非常感謝。 – 2010-03-18 20:01:28

相關問題