LINQ:从类型T的列表中,仅检索某个子类S的对象

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约束.

  • 我在这里错过了什么吗?看起来我们在这里所做的就是将对OfType的调用变为冗余方法. (21认同)
  • 我也没有看到它.难道你不是只为OP提到的相同的linq方法编写一个包装器吗? (4认同)
  • 您可能需要添加“where T : Person”约束,以避免由于拼写错误等原因导致空列表。 (2认同)

kar*_*eem 8

这应该可以解决问题.

var students = persons.Where(p => p.GetType() == typeof(Student));
Run Code Online (Sandbox Code Playgroud)