将 IList<IList<int>> 转换为单个扁平哈希集

Convert IList<IList<int>> to a single flattened hashset

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

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

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

set = { 1,2,3 } 

我试过 megalist.Cast<ISet<int>>().SelectMany(sublist => sublist); 但是 returns 错误:

Unable to cast object of type 'System.Collections.Generic.List'1[System.Int32]' to type 'System.Collections.Generic.ISet'1[System.Int32]'.

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

Is something wrong with the approach?

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

一个Cast<T>运算符意味着外部列表的每个元素必须实际上是类型T,列表不是集合。

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

将序列操作视为工作流

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

从后往前工作。第二步是"sequence turns into set"。因此 "SOMETHING" 必须是 "sequence":

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