Reputation: 101
I have searched, but not found a solution for this. I have made a simple test setup with a List of animals based on the model Animal. I have a new list of giraffes based on the model Giraffe, which is inhereted from Animal.
Is it possible to use AddRange to add from animals to giraffes? Please see my test code below.
internal class Program
{
static List<Animal> animals = new List<Animal>();
static List<Giraffe> giraffes = new List<Giraffe>();
static void Main(string[] args, )
{
animals.Add(new Animal() { AnimalType = "Giraf", AnimalName = "Tall"});
animals.Add(new Animal() { AnimalType = "Elefant", AnimalName = "Huge" });
// this do not work, gives an empty list
// giraffes.AddRange(animals.OfType<Giraffe>());
// this works
AddGiraffe();
animals.Add(new Animal() { AnimalType = "Giraf", AnimalName = "Tall" });
AddGiraffe();
}
static void AddGiraffe()
{
foreach (var ani in animals)
{
if (giraffes.Where(x => x.AnimalType == ani.AnimalType).FirstOrDefault(x => x.AnimalName == ani.AnimalName ) == null)
{
giraffes.Add(new Giraffe()
{
AnimalType = ani.AnimalType,
AnimalName = ani.AnimalName,
legs = 4,
});
}
}
}
}
internal class Animal
{
public string AnimalType { get; set; }
public string AnimalName { get; set; }
}
internal class Giraffe : Animal
{
public int legs { get; set; }
}
Upvotes: 0
Views: 28
Reputation: 141720
You need to add Giraffe
's to your Animals
list, i.e. change the first line of your main method to:
animals.Add(new Giraffe { AnimalType = "Giraf", AnimalName = "Tall", legs = 4});
Check out the docs for Enumerable.OfType<TResult>
:
The
OfType<TResult>(IEnumerable)
method returns only those elements in source that can be cast to typeTResult
Instance of the base class (i.e. new Animal()
) can not be cast to the descendant one because it is not one (i.e. new Animal() is Giraffe
is false).
Read More:
Upvotes: 0