MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37123

work with ICollection and IEnumerable<T>

I have some code expecting an ICollection. Now I want to devide that collection into smaller chunks by grouping them based on a given attribute (all elements within my collection are instances of an abstract base-class, however for legacy code we do not use the generic version of that interface). So what I´d like to achieve is to obtain any enumerable list of collections (one for every group). To get this I planned to convert the ICollection to the generic IEnumerable<T> using the Cast<T>-method on ICollection, and afterwards build a dictionary from that IEnumerable<T> using a LINQ-query. But I fell there might be some better approaches. Do you have any?

public override void DoSomething(ICollection features)
{
    var grp = features.Cast<MyBaseClass>().GroupBy(x => x.table);
    foreach(var g in grp) base.DoSomething(g);
}

EDIT: Hence the base-method (surely) has same signatur (also expects an instance of ICollection) how do I get the values of the groups back to the (non-generic) ICollection?

Upvotes: 0

Views: 148

Answers (1)

Erik Schierboom
Erik Schierboom

Reputation: 16656

I don't think there is anything wrong with your approach, but there is one caveat: if the ICollection instance contains an element that is not of type MyBaseClass, you'll get a cast exception. You can work around this using the OfType extension method, which checks if the element is actually of the type and if so, it casts it to the target type. If the element is of a different type, it is just ignored and no exception is thrown.

public override void DoSomething(ICollection features)
{
    var grp = features.OfType<MyBaseClass>().GroupBy(x => x.table);
    foreach(var g in grp) base.DoSomething((ICollection)g.ToList());
}

You can see a working example here: https://dotnetfiddle.net/0VkedY

Of course, if your requirement is that all elements must be of a specific type, you should use Cast instead of OfType.

Upvotes: 2

Related Questions