2009-09-16 67 views
17

我已經在網上查看了這個,但我要求這個以確保我沒有錯過任何東西。有沒有一個內置函數將HashSets轉換爲C#中的列表?我需要避免元素的重複,但我需要返回一個List。C#哈希集轉換爲列表

回答

48

這是我會怎麼做:

using System.Linq; 
    HashSet<int> hset = new HashSet<int>(); 
    hset.Add(10); 
    List<int> hList= hset.ToList(); 

HashSet的是,根據定義,不包含重複。所以不需要Distinct

+0

與此相關的,如果我有一個有序列表和我做 orderedList.Distinct( ).ToList()你能告訴我它是否保留orderedList中的順序嗎?它符合我的目的,如果它確保它始終保留重複元素的第一次出現並擺脫後來的發生(我有相關性排序的列表...需要保留更相關的列表) – atlantis 2009-09-16 05:25:13

+0

@Ngu there在HashSet中使用Distinct()是沒有意義的,因爲無論如何都不會有重複。 – 2009-09-16 06:00:50

+0

是的,訂單被保留。 – Graviton 2009-09-16 06:24:11

5

有Linq擴展方法ToList<T>()將這樣做(它定義在IEnumerable<T>HashSet<T>實現)。

只要確保你是using System.Linq;

如你顯然意識到HashSet將確保你有沒有重複,這個功能可以讓你把它返回作爲IList<T>

12

兩個等價的選項:

HashSet<string> stringSet = new HashSet<string> { "a", "b", "c" }; 
// LINQ's ToList extension method 
List<string> stringList1 = stringSet.ToList(); 
// Or just a constructor 
List<string> stringList2 = new List<string>(stringSet); 

個人而言,我更喜歡叫ToList是不是就意味着你不需要重申列表的類型。

相反,我以前的想法,左右逢源允許協方差在C#中輕鬆表達4:

HashSet<Banana> bananas = new HashSet<Banana>();   
    List<Fruit> fruit1 = bananas.ToList<Fruit>(); 
    List<Fruit> fruit2 = new List<Fruit>(bananas); 
5
List<ListItemType> = new List<ListItemType>(hashSetCollection);