我有一个清单IAnimal
List<IAnimal> Animals
在这个列表中,我有 3 个不同的Animal
Cat5 个对象Dog10 个对象Cow3 个对象
如何生成 3 个不同的子Animal类型列表?
结果应该是
List<Cat> Cats包含 5 个对象List<Dog> Dogs包含 10 个对象List<Cow> Cows包含 3 个对象
我不介意使用不同的集合类型List。IEnumerable或任何其他人?
我有一个清单IAnimal
List<IAnimal> Animals
在这个列表中,我有 3 个不同的Animal
Cat5 个对象Dog10 个对象Cow3 个对象如何生成 3 个不同的子Animal类型列表?
结果应该是
List<Cat> Cats包含 5 个对象List<Dog> Dogs包含 10 个对象List<Cow> Cows包含 3 个对象我不介意使用不同的集合类型List。IEnumerable或任何其他人?
LINQ 使这变得简单:
var cats = animals.OfType<Cat>().ToList();
var dogs = animals.OfType<Dog>().ToList();
var cows = animals.OfType<Cow>().ToList();
只是使用怎么样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();
foreach使用or遍历您的列表LINQ并检查类型:
foreach(IAnimal animal in Animals){
if(animal is Cat)
Cats.Append(animal);
//do the same with dogs and cows
}