我有IAnimal
通用父集合拆分子集合
List<IAnimal> Animals
这里面列表的列表我有3个不同的Animal
Cat
5个对象Dog
10个对象Cow
3个物品
如何生成3个不同的子Animal
类型的列表?
结果应该是
List<Cat> Cats
包含5个对象List<Dog> Dogs
包含10个对象List<Cow> Cows
包含3个对象
我不介意使用不同的集合类型,然后List
的。 IEnumerable
还是其他?
我有IAnimal
通用父集合拆分子集合
List<IAnimal> Animals
这里面列表的列表我有3个不同的Animal
Cat
5个对象Dog
10个对象Cow
3个物品如何生成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();
迭代通过使用foreach
或LINQ
并检查类型列表:
foreach(IAnimal animal in Animals){
if(animal is Cat)
Cats.Append(animal);
//do the same with dogs and cows
}
请注意,你必须投,而且方法'Add',不'Append'。 – 2013-03-09 14:35:33
如何只使用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();
大,非常感谢 – Maro 2013-03-09 13:07:29