tags:

views:

184

answers:

5

Maybe the need to do this is a 'design smell' but thinking about another question, I was wondering what the cleanest way to implement the inverse of this:

foreach(ISomethingable somethingableClass in collectionOfRelatedObjects)
{
  somethingableClass.DoSomething();
}

i.e. How to get/iterate through all the objects that don't implement a particular interface?

Presumably you'd need to start by upcasting to the highest level:

foreach(ParentType parentType in collectionOfRelatedObjects)
{
  // TODO: iterate through everything which *doesn't* implement ISomethingable 
}

Answer by solving the TODO: in the cleanest/simplest and/or most efficient way

+6  A: 

Something like this?

foreach (ParentType parentType in collectionOfRelatedObjects) {
    if (!(parentType is ISomethingable)) {
    }
}
J D OConal
+3  A: 

Probably best to go all the way and improve the variable names:

foreach (object obj in collectionOfRelatedObjects)
{
    if (obj is ISomethingable) continue;

    //do something to/with the not-ISomethingable
}
Tim Erickson
A: 

J D OConal's is the best way to do this but as a side note, you can use the as keyword to cast an object, and it'll return null if its not of that type.

So something like:

foreach (ParentType parentType in collectionOfRelatedObjects) {
    var obj = (parentType as ISomethingable);
    if (obj == null)  {
    }
}
sontek
+3  A: 

this should do the trick:

collectionOfRelatedObjects.Where(o => !(o is ISomethingable))
Jay Bazuzi
Nice. I haven't done too much with these new methods.
J D OConal
A: 

With some help from the LINQ extension method OfType<>(), you can write:

using System.Linq;

...

foreach(ISomethingable s in collection.OfType<ISomethingable>())
{
  s.DoSomething();
}
Yacoder