code_junkie

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

Nov 13th, 2011
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.76 KB | None | 0 0
  1. IList<Aniamls> chickens;
  2. IList<Animals> farmAnimals; // only contains the cows and sheep, now.
  3.  
  4. public abstract class Animal {}
  5.  
  6. public class Chicken : Animal {}
  7.  
  8. var chickens = animals.OfType<Chicken>().Cast<Animal>().ToList();
  9.  
  10. var nonChickens = animals.Except(chickens).ToList();
  11.  
  12. var chickens = new List<Animal>();
  13. var nonChickens = new List<Animal>();
  14.  
  15. foreach(var animal in animals)
  16. {
  17. var list = animal is Chicken ? chickens : nonChickens;
  18.  
  19. list.Add(animal);
  20. }
  21.  
  22. var chickens = farmAnimals.ToList().FindAll (c => c.Type == "Chicken");
  23. farmAnimals.RemoveAll(a => a.Type=="Chicken");
  24.  
  25. var chickens = farmAnimals.Where(a => a.GetType() == typeof(Chicken)).ToList();
  26. farmAnimals = farmAnimals.Where(a => a.GetType() != typeof(Chicken)).ToList();
Add Comment
Please, Sign In to add comment