views:

141

answers:

2

Hi,

I am working with a generic data structure, say MyGeneric<Type>. There is a case where I have to iterate over all the values it holds

The code I am trying to do.

for ( all the keys in myGeneric ) {
    // do lot of stuff here 
}

Now the generic can hold base type as double and string and it can hold some user-defined type also. There is a particular situation where I have to some specific work depending upon the type of the generic.

so the final code block looks something like this

for( all the keys in myGeneric ) {
    if key is type foo then 
     //do foo foo 
    else if key is of type bar 
     //do bar bar 
}

Now, as complexity sensitive as I am I do not like to have an if condition in the for loop. So the next solution I did was

if myGeneric is of type foo 
    call fooIterator(myGeneric) 
if myGenric is of type bar 
    call barItetrator(myGeneric)


function FooIterator() {
    // .....
    // foo work 
    //......
}

function BarItetrator() {
    // .....
    // bar work 
    //......
}

Then again when somebody sees my code then I am quite sure that they will shout where is the "refactoring".

What is the ideal thing to do in this situation ?

Thanks.

+7  A: 

Well, you could use the Linq OfType<T> method, and multiple loops?

foreach(Foo foo in list.OfType<Foo>()) {
  //
}
foreach(Bar bar in list.OfType<Bar>()) {
  //
}

Beyond that, you're into conditional statements. I did look at this here in relation to F#, which does this more cleanly.

As an aside; if this was using PushLINQ (in MiscUtil) you could do this in a single iteration, by pushing the different types through different branches - not sure it warrants it just for this, though.

Marc Gravell
A: 

I think your second option reads a little better. Specially if the foo/bar work contains a lot of code. In terms of performance, I expect a marginal lost in calling a method but I don't think it will affect you.

bruno conde