Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ: From a list of type T, retrieve only objects of a certain subclass S

Given a simple inheritance hierarchy: Person -> Student, Teacher, Staff

Say I have a list of Persons, L. In that list are some Students, Teachers, and Staff.

Using LINQ and C#, is there a way I could write a method that could retrieve only a particular type of person?

I know I can do something like:

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.

like image 950
Hythloth Avatar asked Jul 26 '09 16:07

Hythloth


2 Answers

This should do the trick.

var students = persons.Where(p => p.GetType() == typeof(Student)); 
like image 27
kareem Avatar answered Sep 28 '22 05:09

kareem


you can do this:

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

EDIT: added the where constraint.

like image 193
Mladen Prajdic Avatar answered Sep 28 '22 05:09

Mladen Prajdic