0

我正在尝试Concat()在多个 ISet 上使用来制作一个更大的 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或某种。

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

4

3 回答 3

2

LINQ 函数,例如Concat返回一个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));
于 2011-08-05T11:22:17.227 回答
1

你可以尝试这样的事情:

ISet<Faa> result = items.Values.Aggregate(new HashSet<Faa>(),
                                          (a, x) => { a.UnionWith(x)); return a; });
于 2011-08-05T11:20:59.007 回答
0

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

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

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

于 2011-08-05T11:26:08.650 回答