Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract some data from a collection using lambda/linq to objects?

i have an IList<Animals> farmAnimals;

this list has three types,

  • Cows
  • Sheep
  • Chickens

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!

CLARIFICATION QUESTION:

what is more performant? FindAll & RemoveAll versus the Where suggestion?

like image 749
Pure.Krome Avatar asked Nov 25 '25 10:11

Pure.Krome


2 Answers

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);
}
like image 125
Bryan Watts Avatar answered Nov 28 '25 00:11

Bryan Watts


var chickens = farmAnimals.Where(a => a.GetType() == typeof(Chicken)).ToList();
farmAnimals = farmAnimals.Where(a => a.GetType() != typeof(Chicken)).ToList();
like image 36
Brett Avatar answered Nov 27 '25 23:11

Brett



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!