【问题标题】:Convert IList<IList<int>> to a single flattened hashset将 IList<IList<int>> 转换为单个扁平化的哈希集
【发布时间】:2018-09-24 23:38:39
【问题描述】:

我有一个列表,其中包含如下数据:

megalist = { new List {1,2}, new List {1,2}, new List{3}};

现在,我想将这个 IList 列表转换为一个扁平化的 hashset,应该如下所示:

set = { 1,2,3 } 

我试着做 megalist.Cast&lt;ISet&lt;int&gt;&gt;().SelectMany(sublist =&gt; sublist); 但返回错误:

无法将“System.Collections.Generic.List'1[System.Int32]”类型的对象转换为“System.Collections.Generic.ISet'1[System.Int32]”类型。

这种方法有问题吗? 非常感谢。

【问题讨论】:

  • Is something wrong with the approach? 是的。您不能将List&lt;T&gt;(或IList&lt;T&gt;)转换为ISet&lt;T&gt;,因为这两件事(或代表的事物)在本质上彼此完全不同......
  • 建议:先将IList&lt;IList&lt;T&gt;&gt; 展平,然后将结果输入新的HashSet&lt;T&gt;

标签: c# list casting ienumerable


【解决方案1】:

这种方法有问题吗?

这是一个奇怪的问题,因为很明显你已经知道答案了。是的,这是错误的方法,因为它会在运行时崩溃。

Cast&lt;T&gt; 运算符意味着外部列表的每个元素实际上必须是T 类型,并且列表不是集合。

退后一步。你有什么?一个序列的序列。你想要什么?一套。您可以使用什么来设置后端? A method ToHashSet that turns sequences into sets.

将序列操作视为工作流程

Sequence of sequences --first step--> SOMETHING --second step--> Set

从后向前工作。第二步是“序列转集”。因此“SOMETHING”必须是“序列”:

Sequence of sequences -first step-> Sequence -ToHashSet-> Set

现在我们需要一个将序列序列转换为序列的步骤。你知道该怎么做:

Sequence of sequences --SelectMany--> Sequence --ToHashSet--> Set

现在你可以编写代码了:

ISet<int> mySet = megalist.SelectMany(x => x).ToHashSet();

你已经完成了。


快速更新:Luca 在评论中指出 ToHashSet 并非在所有版本的 .NET 中都可用。没有的话,自己写单行:

static class MyExtensions
{
  public static HashSet<T> ToHashSet<T>(this IEnumerable<T> items)
  {
    return new HashSet<T>(items);
  }
}

【讨论】:

  • ToHashSet 仅在 .NET Framework 4.7.2 中可用。如果您需要以前版本的 .NET Framework,您可以使用正确的HashSet constructor,它将序列作为输入。
猜你喜欢
  • 1970-01-01
  • 2018-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-06
  • 1970-01-01
  • 2020-05-17
相关资源
最近更新 更多