Hyt*_*oth 32 c# linq typeof oftype
给定一个简单的继承层次结构:人员 - >学生,教师,员工
假设我有一个人员名单,L.在该名单中有一些学生,教师和工作人员.
使用LINQ和C#,有没有办法可以编写一个只能检索特定类型的人的方法?
我知道我可以这样做:
var peopleIWant = L.OfType< Teacher >();
Run Code Online (Sandbox Code Playgroud)
但我希望能够做一些更有活力的事情.我想编写一个方法来检索我能想到的任何类型的Person的结果,而不必为每种可能的类型编写方法.
Mla*_*dic 47
你可以这样做:
IList<Person> persons = new List<Person>();
public IList<T> GetPersons<T>() where T : Person
{
return persons.OfType<T>().ToList();
}
IList<Student> students = GetPersons<Student>();
IList<Teacher> teacher = GetPersons<Teacher>();
Run Code Online (Sandbox Code Playgroud)
编辑:添加了where约束.
这应该可以解决问题.
var students = persons.Where(p => p.GetType() == typeof(Student));
Run Code Online (Sandbox Code Playgroud)