Home > OS >  How can I get a specific object of specific type from list of objects
How can I get a specific object of specific type from list of objects

Time:08-03

I have an animal manager class that has a list of object that implement the IAnimal interface. It has a method that must get the cats only from that same list. How can i design my code in a better way to achieve this ?

Sample code below (in C#)

public interface IAnimal
{
    void doSomeThing();
}

public class Cat : IAnimal
{
    public void doSomeThing()
    {
        Console.WriteLine("Cat");
    }
}

public class Dog : IAnimal
{
    public void doSomeThing()
    {
        Console.WriteLine("Dog");
    }
}

public class AnimalManager
{
    private List<IAnimal> animals = new List<IAnimal>();

    private void manageCat()
    {
     //get cats from animals list.
    }
}

CodePudding user response:

var cats = animals.OfType<Cat>()

CodePudding user response:

Just compare the type:

public class AnimalManager
{
     private List<IAnimal> animals = new List<IAnimal>();

     private void manageCat()
     {
           var OnlyCats = animals.Where(animal => animal.GetType() == typeof(cat)); 
     }
}
  • Related