How to get a specific derived object in List <T>?

Say I have a generic Fruit list ( List<Fruit> fruits = new List<Fruit>() ). Then I add a couple of objects (all derived from Fruit ) - Banana , Apple , Orange , but with different properties on derived objects (for example, Banana.IsYellow ).

 List<Fruit> fruits = new List<Fruit>(); Banana banana1 = new Banana(); Banana banana2 = new Banana(); Apple apple1 = new Apple(); Orange orange2 = new Orange(); fruits.Add(banana1); fruits.Add(banana2); fruits.Add(apple1); fruits.Add(orange1); 

Then I can do it:

 foreach(Banana banana in fruits) Console.Write(banana.IsYellow); 

But at runtime, of course, this is not true, because there are no IsYellow objects for Apple and Orange objects.

How can I get only bananas, apples, oranges, etc. from List<Fruit> ?

+7
collections list c # filter
source share
5 answers
 foreach(Banana b in fruits.OfType<Banana>()) 
+31
source share

You could just do

 foreach(Fruit fruit in fruits) { Banana b = fruit as Banana; if(b != null) { Console.Write(b.IsYellow); } } 
+3
source share

Step 1: First you must make a sub-list from the Fruit list. To make this list, use the function Generic FindAll() and Predicate .

Step 2: Later in the subset, you can iterate containing only the β€œbanana”

Here is the code

Step 1:

 List<Fruit> fruits = new List<Fruit>(); Banana banana1 = new Banana(); Banana banana2 = new Banana(); Apple apple1 = new Apple(); Orange orange1 = new Orange(); fruits.Add(banana1); fruits.Add(banana2); fruits.Add(apple1); fruits.Add(orange1); //Extract Banana from fruit list List<Fruit> bananaComb = fruits.FindAll(IsBanana); //Now iterate without worring about which fruit it is foreach (Fruit fruit in bananaComb) { Console.WriteLine(((Banana)fruit).IsYellow); } 

Step 2: The predicate function is used here.

 //A Predicate function to determine whether its a Banana static protected bool IsBanana(Fruit aFruit) { return aFruit.GetType().Name == "Banana" ? true : false; } 
+3
source share

Personally, I find this method more readable:

 foreach(Fruit fruit in fruits) { if (fruit is Banana) { Banana b = fruit as Banana; Console.Write(b.IsYellow); } else if (fruit is Apple) { // ... } } 
+1
source share

adding another syntax though .OfType <Banana> () is probably the best.

 foreach (Banana b in fruits.Where(x => x is Banana)) 
+1
source share

All Articles