【问题标题】:HashSet conversion to ListHashSet 转换为 List
【发布时间】:2009-09-16 04:45:27
【问题描述】:

我在网上查到了这个,但我问这个是为了确保我没有错过任何东西。 C# 中是否有将 HashSets 转换为 Lists 的内置函数?我需要避免元素的重复,但我需要返回一个列表。

【问题讨论】:

    标签: c# list set


    【解决方案1】:

    我会这样做:

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

    根据定义,HashSet 不包含重复项。所以不需要Distinct

    【讨论】:

    • 与此相关,如果我有一个有序列表并且我执行了orderedList.Distinct().ToList() 你能告诉我它是否保留orderedList 中的顺序吗?如果它确保它始终保留第一次出现的重复元素并消除后来出现的重复元素,它就符合我的目的。(我有按相关性排序的列表......需要保留更相关的一个)
    • @Ngu 在 HashSet 上使用 Distinct() 是没有意义的,因为无论如何都不会有重复项
    • @Simon...正是我想知道的...知道为什么在 HashSet 上有一个可用的 Distinct() 方法吗?
    • @atlantis - Distinct 带有可枚举
    【解决方案2】:

    两个等效选项:

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

    【讨论】:

      【解决方案3】:

      有 Linq 扩展方法 ToList&lt;T&gt;() 可以做到这一点(它在 IEnumerable&lt;T&gt; 上定义,由 HashSet&lt;T&gt; 实现)。

      只要确定你是using System.Linq;

      您显然知道HashSet 将确保您没有重复,并且此函数将允许您将其作为IList&lt;T&gt; 返回。

      【讨论】:

        【解决方案4】:
        List<ListItemType> = new List<ListItemType>(hashSetCollection);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-09-12
          • 1970-01-01
          • 1970-01-01
          • 2011-07-25
          • 1970-01-01
          • 2023-01-19
          • 1970-01-01
          相关资源
          最近更新 更多