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; }
}
You need to add
Giraffe's to yourAnimalslist, i.e. change the first line of your main method to:Check out the docs for
Enumerable.OfType<TResult>: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 Giraffeis false).Read More: