开发者

Concatenate an ISet using Aggregate

I am trying to use Concat() on multiple ISets to make one larger ISet. So I tried the following piece of code:

public class Foo
{
    private Dictionary<Bii, ISet<Faa>开发者_JS百科> items = new Dictionary<Bii, ISet<Faa>>();

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

The problem is that this results in a Compiler error:

Cannot implicitly convert type System.Collections.Generic.IEnumerable<Faa> to System.Collections.Generic.ISet<Faa>. An explicit conversion exists (are you missing a cast?)

And a second error:

Cannot convert lambda expression to delegate type System.Func<System.Collections.Generic.ISet<Faa>,System.Collections.Generic.ISet<Faa>,System.Collections.Generic.ISet<Faa>> because some of the return types in the block are not implicitly convertible to the delegate return type

I also tried using a cast like:

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

But this will give me an InvalidCastException, because it should be a ConcatIterator or some sort.

How can I do a good cast to join all ISets to one ISet?


LINQ functions such as Concat returns an IEnumerable. There is no ISet anymore after this call. You can rebuild one though:

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

Or, using SelectMany to simplify:

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


You could try something like this:

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


If you don't want to change any of the incoming sets you can do something like this:

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

If you don't want to introduce a concrete type you could append to the first incoming Set but then you would have altered that which is less than stellar.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜