HashSet conversion to List

后端 未结 4 1784
时光说笑
时光说笑 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条回答
  •  -上瘾入骨i
    2021-01-07 16:58

    Two equivalent options:

    HashSet stringSet = new HashSet { "a", "b", "c" };
    // LINQ's ToList extension method
    List stringList1 = stringSet.ToList();
    // Or just a constructor
    List stringList2 = new List(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 bananas = new HashSet();        
        List fruit1 = bananas.ToList();
        List fruit2 = new List(bananas);
    

提交回复
热议问题