I have a base class, called NodeUpgrade, which have several child types. An example of a specific child class is FactoryUpgrade.
I have a list of NodeUpgrades, which can be a mix of different child types. How do I write a linq query to retrieve a type of NodeUpgrade and cast to that specific type?
My working query looks something like this:
var allFactories = (from Node n in assets.Nodes
from FactoryUpgrade u in n.NodeUpgrades
where u.ClassID == NodeUpgradeTypes.Factory
select u)
This, of course, doesn’t work. Can I specify the final type of the output?
If you are sure that every type in a sequence is a given type, you can use the
Cast<T>()extension method. If there can be multiple types in the list and you only want one of them, you can useOfType<T>()to filter the sequence.The difference is that
Castwill throw an exception if an animal isn’t a cat, whereasOfTypewill perform a type check before actually trying the conversion. I would favorCastoverOfTypewhen you are confident of the uniform type. (Also note that these do not perform user-defined conversions. If you have defined an implicit or explicit conversion, those will not be supported by these methods.)The resulting sequence in each case will be
IEnumerable<Cat>, which you can do further query operations on (filters, groupings, projections,ToList(), etc.)