Aph*_*ion 8 c# linq linq-to-objects
如何使用linq-to-objects基于派生类型过滤掉对象?
我正在寻找性能最佳的解决方案.
使用的类:
abstract class Animal { }
class Dog : Animal { }
class Cat : Animal { }
class Duck : Animal { }
class MadDuck : Duck { }
Run Code Online (Sandbox Code Playgroud)
我知道三种方法:使用is关键字,使用Except方法,并使用该OfType方法.
List<Animal> animals = new List<Animal>
{
new Cat(),
new Dog(),
new Duck(),
new MadDuck(),
};
// Get all animals except ducks (and or their derived types)
var a = animals.Where(animal => (animal is Duck == false));
var b = animals.Except((IEnumerable<Animal>)animals.OfType<Duck>());
// Other suggestions
var c = animals.Where(animal => animal.GetType() != typeof(Duck))
// Accepted solution
var d = animals.Where(animal => !(animal is Duck));
Run Code Online (Sandbox Code Playgroud)
如果你想要排除Duck的子类,那么is最好.您可以将代码简化为.Where(animal => !(animal is Duck));
否则,sll对GetType的推荐是最好的
| 归档时间: |
|
| 查看次数: |
2088 次 |
| 最近记录: |