【发布时间】:2017-03-17 11:49:56
【问题描述】:
假设我们有动物、狗和猫类。 Dog 和 Cat 都扩展了 Animal。
public class Animal{}
public class Dog : Animal{}
public class Cat : Animal{}
然后我们创建一个动物哈希集并用猫和狗填充它。
HashSet<Animal> animals = new HashSet<Animal>();
animals.Add(new Dog());
animals.Add(new Cat());
animals.Add(new Dog());
animals.Add(new Cat());
获取哈希集动物中包含的所有狗(除了狗之外什么都没有)的哈希集或列表的最佳方法是什么?
【问题讨论】:
-
您只能在
HashSet<>中搜索完全相等,而不是“相似”...所以您必须枚举所有HashSet<> -
点赞
var dogs = animals.Where(x => x is Dog) -
animals.Where(x => x.GetType() == typeof(Dog)); -
或:
animals.OfType<Dog>() -
@Juraboros 你想做什么?如果您想根据它们的类型处理所有项目,带有一点模式匹配的简单循环既简单又干净。如果您只想处理猫或狗,则必须遍历所有内容或使用不同的容器。这样的要求将是相当不寻常的。甚至
OfType<Dog>()也会遍历源并将类型应用为过滤器
标签: c#