i have an IList<Animals> farmAnimals;
this list has three types,
how can i remove all the Chickens from the list using a lambda query or linq-to-objects so i have a separate list of chickens and the original list now only has cows and sheep.
Do i have to make three lists (the original + 2 new ones, filtered) and then null the original list? or is there a trickier way?
result needs to be
IList<Aniamls> chickens;
IList<Animals> farmAnimals; // only contains the cows and sheep, now.
cheers!
what is more performant? FindAll & RemoveAll versus the Where suggestion?
Assuming:
public abstract class Animal {}
public class Chicken : Animal {}
you can do:
var chickens = animals.OfType<Chicken>().Cast<Animal>().ToList();
var nonChickens = animals.Except(chickens).ToList();
Edit
Any reasonable answer should be O(n), meaning each item in the original list is only processed once. Therefore, I would suggest an imperative approach:
var chickens = new List<Animal>();
var nonChickens = new List<Animal>();
foreach(var animal in animals)
{
var list = animal is Chicken ? chickens : nonChickens;
list.Add(animal);
}
var chickens = farmAnimals.Where(a => a.GetType() == typeof(Chicken)).ToList();
farmAnimals = farmAnimals.Where(a => a.GetType() != typeof(Chicken)).ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With