【问题标题】:Concatenate an ISet using Aggregate使用 Aggregate 连接 ISet
【发布时间】:2011-08-05 11:15:09
【问题描述】:

我试图在多个 ISet 上使用 Concat() 来制作一个更大的 ISet。所以我尝试了以下代码:

public class Foo
{
    private Dictionary<Bii, ISet<Faa>> items = new Dictionary<Bii, ISet<Faa>>();

    public ISet<Faa> GetCompleteList()
    {
        ISet<Faa> result = items.Values.Aggregate((x,y) => x.Concat(y));
        return result;
    }
}

问题是这会导致编译器错误:

无法将类型 System.Collections.Generic.IEnumerable&lt;Faa&gt; 隐式转换为 System.Collections.Generic.ISet&lt;Faa&gt;。存在显式转换(您是否缺少演员表?)

还有第二个错误:

无法将 lambda 表达式转换为委托类型 System.Func&lt;System.Collections.Generic.ISet&lt;Faa&gt;,System.Collections.Generic.ISet&lt;Faa&gt;,System.Collections.Generic.ISet&lt;Faa&gt;&gt;,因为块中的某些返回类型不能隐式转换为委托返回类型

我也尝试过使用这样的演员:

ISet<Faa> result = items.Values.Aggregate((x,y) => (ISet<Faa>)x.Concat(y));

但这会给我一个InvalidCastException,因为它应该是ConcatIterator 或某种形式。

如何进行良好的演员表以将所有 ISet 加入一个 ISet?

【问题讨论】:

    标签: c# set-theory


    【解决方案1】:

    Concat 等 LINQ 函数返回一个 IEnumerable。此次通话后不再有ISet。你可以重建一个:

    ISet<Faa> result = new HashSet<Faa>(items.Values.Aggregate((x,y) => x.Concat(y)));
    

    或者,使用SelectMany 来简化:

    ISet<Faa> result = new HashSet<Faa>(items.Values.SelectMany(value => value));
    

    【讨论】:

      【解决方案2】:

      你可以试试这样的:

      ISet<Faa> result = items.Values.Aggregate(new HashSet<Faa>(),
                                                (a, x) => { a.UnionWith(x)); return a; });
      

      【讨论】:

      • 虽然Julien's second suggestion using SelectMany 更可取,但imo。
      • 你能告诉我为什么吗?它更快吗?
      • @Marnix:我认为SelectMany 版本更简单,更易读。我希望性能几乎完全相同(HashSet&lt;T&gt; 构造函数可能使用UnionWith 或等效的幕后)。不过,您必须进行基准测试才能确定。
      【解决方案3】:

      如果您不想更改任何传入的集合,您可以执行以下操作:

      public ISet<Faa> GetCompleteList()
      {
          ISet<Faa> result = new HashSet<Faa>(items.Values.SelectMany(x => x));
          return result;
      }
      

      如果您不想引入具体类型,则可以附加到第一个传入的 Set 中,但是您会更改不那么出色的类型。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-02
        • 2019-05-09
        • 1970-01-01
        • 2013-04-11
        • 2018-10-24
        相关资源
        最近更新 更多