I have a dictionary of objects, all of different types but derived from the same base class, and wanted to find a specific one. I thought I could filter the dictionary for objects of a given type using “.OfType()”, but didn’t find anything.
What did I not understand ?
class Program
{
static Dictionary<String, Animal> critters;
static void Main(string[] args)
{
critters = new Dictionary<String, Animal>();
critters.Add("Tiddles", new Cat());
critters.Add("Rover", new Dog());
critters.Add("Bob", new Fish());
Animal rover = GetAnimal<Dog>();
}
// Finds first animal of the specified type.
static T GetAnimal<T>() where T : Animal
{
var qry = from animal in critters.OfType<T>()
select animal;
return (qry.Count() > 0) ? qry.First() : null;
}
}
class Animal { }
class Dog : Animal { }
class Cat : Animal { }
class Fish : Animal { }
Thanks,
Ross
It is because dictionary IEnumarable is returning a
<KeyValuePair<TKey, TValue>. Use the Values from it.I would also suggest that you change the last line in your GetAnimal from
There is no need to waste a .Count() operation on qry, just use FirstOrDefault, it does the same thing.
You can reduce it, and not lose any readability, to: