LINQ:从类型 T 的列表中,仅检索某个子类 S 的对象 [英] LINQ: From a list of type T, retrieve only objects of a certain subclass S

查看:22
本文介绍了LINQ:从类型 T 的列表中,仅检索某个子类 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 >();

但我希望能够做一些更有活力的事情.我想编写一个方法来检索我能想到的任何类型的 Person 的结果,而不必为每种可能的类型编写一个方法.

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>();

添加 where 约束.

added the where constraint.

这篇关于LINQ:从类型 T 的列表中,仅检索某个子类 S 的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆