So I have a collection of objects. The objects are of differing type, but all of the types derive from a single base class. I want to iterate through the collection, check for objects of a specific derived type, and call a method in the base class for those objects. This is what I have:
dim DogQuery = From Dog as DogBase in DogCollection
Where Dog.GetType = GetType(DogBeagle)
Select Dog
For Each d as DogBase in DogQuery
d.Feed()
Next
...but it seems inelegant. Especially when...
For Each Dog as DogBase in DogCollection
If Dog.GetType = GetType(DogBeagle) then
Dog.Feed()
End If
Next
...accomplishes the same thing in (subjectively) tighter code.
My reading on immediate execution suggests that the only way to do what I want is to have the LINQ return a singleton or call something like .ToList(). Is there a way to get immediate execution without needing the extra step? Or is this just a case of LINQ being overkill for the task at hand?
Deferred/immediate execution isn't relevant here. If you called ToList()
, that wouldn't change anything.
There are two options to make this simpler though.
Firstly, if you don't need it to be the exact Dog
type, but DogBeagle
or anything that derives from DogBeagle
, you could use OfType
:
For Each d As DogBeagle in DogCollection.OfType(Of DogBeagle)()
d.Feed()
Next
If you really do want the exact type, you can use the fact that you're only really using a Where
clause - you're not transforming the result. As such, LINQ isn't an overkill, but a query expression is... you can just use Where
directly:
For Each d As Dog in DogCollection.Where(Function(x) x.GetType() = GetType(DogBeagle))
d.Feed()
Next
See more on this question at Stackoverflow