简体   繁体   中英

How do I get a particular derived object in a List<T>?

Let's say I have a generic list of Fruit ( List<Fruit> fruits = new List<Fruit>() ). I then add a couple of objects (all derived from Fruit ) - Banana , Apple , Orange but with different properties on the derived objects (such as 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 this:

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

But at execution time of course this is not valid because there is no IsYellow -property on the Apple and Orange objects.

How do I get only the bananas, apples, oranges etc from the List<Fruit> ?

foreach(Banana b in fruits.OfType<Banana>())

You could just do

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

Step 1: First you should make sub-list from Fruit list. To make the sub-list use Generic's FindAll() and Predicate function.

Step 2: Later, in the sub-set you can iterate, which contains only 'Banana'

Here is the code

Step1:

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: Here comes predicate function

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

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)
   {
      // ...
   }
}

添加另一种语法,尽管.OfType <Banana>()可能是最好的。

foreach (Banana b in fruits.Where(x => x is Banana))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM