通用父集合拆分为子集合

时间:2013-03-09 12:44:35

标签: c# list .net-3.5 ienumerable

我有IAnimal

的列表
List<IAnimal> Animals

在此列表中,我有3个不同的Animal

  1. Cat 5个对象
  2. Dog 10个对象
  3. Cow 3个对象
  4. 如何生成3个不同的子Animal类型列表?

    结果应为

    1. List<Cat> Cats包含5个对象
    2. List<Dog> Dogs包含10个对象
    3. List<Cow> Cows包含3个对象
    4. 我不介意使用不同的集合类型ListIEnumerable或其他任何人?

3 个答案:

答案 0 :(得分:6)

LINQ使这很简单:

var cats = animals.OfType<Cat>().ToList();
var dogs = animals.OfType<Dog>().ToList();
var cows = animals.OfType<Cow>().ToList();

答案 1 :(得分:4)

如何使用Enumerable.OfType

  

根据指定的类型过滤IEnumerable的元素。

Return Value
Type: System.Collections.Generic.IEnumerable<TResult>
An IEnumerable<T> that contains elements from the input sequence of type TResult.

var cat = animals.OfType<Cat>().ToList();
var cow = animals.OfType<Cow>().ToList();
var dog = animals.OfType<Dog>().ToList();

答案 2 :(得分:0)

使用foreachLINQ对您的列表进行迭代,并检查类型:

 foreach(IAnimal animal in Animals){
  if(animal is Cat)
     Cats.Append(animal);
 //do the same with dogs and cows
 }