LINQ:从T类型的列表,检索某个子类的S仅对象 [英] LINQ: From a list of type T, retrieve only objects of a certain subclass S
问题描述
给出一个简单的继承层次:
人 - >学生,教师和工作人员
Given a simple inheritance hierarchy: Person -> Student, Teacher, Staff
说我有人员名单,L.
在该名单是一些学生,教师和工作人员。
Say I have a list of Persons, L. In that list are some Students, Teachers, and Staff.
使用LINQ和C#的,是有办法,我可以写,可以只检索某一特定类型的人的方法?
Using LINQ and C#, is there a way I could write a method that could retrieve only a particular type of person?
我知道我可以这样做:
var peopleIWant = L.OfType< Teacher >();
不过,我希望能够做一些更有活力。我想编写,将检索我能想到的任何类型的人的结果的方法,而无需编写每一个可能的类型的方法。
But I want to be able to do something more dynamic. I would like to write a method that will retrieve results for any type of Person I could think of, without having to write a method for every possible type.
推荐答案
你可以这样做:
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>();
编辑:加入其中,约束
added the where constraint.
这篇关于LINQ:从T类型的列表,检索某个子类的S仅对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!