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

i has IList<Animals> farmAnimals;

this list has three types,

  • Cows
  • Sheeps
  • Chickens

how can I remove all chickens from the list using lambda query or linq-to-objects, so I have a separate list of chickens, and in the original list now there are only a cow and sheep.

Do I need to make three lists (original + 2 new, filtered) and then delete the original list? or is there a more complicated way?

the result should be

IList<Aniamls> chickens;
IList<Animals> farmAnimals; // only contains the cows and sheep, now.

Hurrah!

QUESTION OF COMPLETION:

which is more effective? FindAll and RemoveAll vs. Where?

+3
source share
4 answers

Assuming that:

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

O (n), . :

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);
}
+3
var chickens = farmAnimals.ToList().FindAll (c => c.Type == "Chicken");
farmAnimals.RemoveAll(a => a.Type=="Chicken");
+2
var chickens = farmAnimals.Where(a => a.GetType() == typeof(Chicken)).ToList();
farmAnimals = farmAnimals.Where(a => a.GetType() != typeof(Chicken)).ToList();
+2

var Chickens = farmAnimals.FindAll (a => a - chicken);

I have a terrible tendency to influence the simplest solution. In this case, using lambda only requires the .NET framework 2.0. LINQ extension methods require 3.5.

0
source

All Articles