使用Aggregate连接集合

时间:2011-08-05 11:15:10

标签: c# set-theory

我正在尝试在多个ISets上使用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<Faa>类型隐式转换为System.Collections.Generic.ISet<Faa>。存在显式转换(您是否错过了演员?)

还有第二个错误:

  

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

我也尝试使用类似的演员:

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

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

如何将所有ISets加入一个ISet?

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

您可以尝试这样的事情:

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

答案 2 :(得分:0)

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

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

如果你不想引入一个具体的类型,你可以附加到第一个传入的集合,但是你会改变那个小于恒星的那个。

相关问题