ForEach-ing only certain objects in a list

, , 1 Kommentar »

Jeremy from Digital Blasphemy brought up the question of how to iterate only over certain objects in a list. In his example, he has a list filled with Cats and Dogs where both are inherited from the base class Animal. What he wanted to do is to use a foreach statement to iterate over the Dogs only without any kind of filtering inside the foreach loop. I pointed out that this is easy to achieve using an anonymous delegate as the predicate in the FindAll method of the List type. The code looks like that:

List<Animal> animals = new List<Animal>();
animals.Add(new Cat("Fluffy"));
animals.Add(new Dog("Spot"));
animals.Add(new Dog("Lucky"));
animals.Add(new Cat("Frisky"));
animals.Add(new Dog("Fido"));
foreach (Dog dog in animals.FindAll(delegate(Animal a) {return a is Dog;}))
{
  Console.WriteLine("Found a dog named " + dog.Name);
}

C#

, Keine Kommentare »

Schauen wir doch mal aus welcher Stadt in Google hauptsächlich nach "C#" gesucht wird. Huch, das war ja zu erwarten…

WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Anmelden