HashSet conversion to List

后端 未结 4 1770
时光说笑
时光说笑 2021-01-07 16:17

I have looked this up on the net but I am asking this to make sure I haven\'t missed out on something. Is there a built-in function to convert HashSets to Lists in C#? I nee

相关标签:
4条回答
  • 2021-01-07 16:58

    Here's how I would do it:

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

    HashSet is, by definition, containing no duplicates. So there is no need for Distinct.

    0 讨论(0)
  • 2021-01-07 16:58

    Two equivalent options:

    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);
    

    Personally I'd prefer calling ToList is it means you don't need to restate the type of the list.

    Contrary to my previous thoughts, both ways allow covariance to be easily expressed in C# 4:

        HashSet<Banana> bananas = new HashSet<Banana>();        
        List<Fruit> fruit1 = bananas.ToList<Fruit>();
        List<Fruit> fruit2 = new List<Fruit>(bananas);
    
    0 讨论(0)
  • 2021-01-07 17:05

    There is the Linq extension method ToList<T>() which will do that (It is defined on IEnumerable<T> which is implemented by HashSet<T>).

    Just make sure you are using System.Linq;

    As you are obviously aware the HashSet will ensure you have no duplicates, and this function will allow you to return it as an IList<T>.

    0 讨论(0)
  • 2021-01-07 17:22
    List<ListItemType> = new List<ListItemType>(hashSetCollection);
    
    0 讨论(0)
提交回复
热议问题