Freddy
Freddy

Reputation: 876

LINQ use OfType() with given Type to get class

I want to filer a List<IA> of the type IA (an interface). Let's say I have the following structure:

interface IA {
    // Some definitions here...
}
class B : IA {}
class C : IA {}

I want to filter the list for B and C using LINQ. Normally, I would use the myList.OfType<B>().ToList() method but since I don't know in my method, what type I want to filter for, I need to find the base type of the list which I am doing with:

Type[] types = myList.GetType().GetGenericArguments();
// type[0] == typeof(B)

Now I want to do something like:

List<IA> filteredList = myList.OfType<type[0]>().ToList();

This doesn't work for the obvious reason that OfType<>() accepts only a class and not a type. My question is: How do I come from a type back to a class?

Edit: Changed the result I want to achieve from List<type[0]> to List<IA>.

Edit2: A working minimal example

class Program
{
    static List<IExample> exampleList;

    static void Main(string[] args)
    {
        exampleList = new List<IExample>();

        A a = new A();
        B b = new B();

        exampleList.Add(a);
        exampleList.Add(b);

        List<IExample> anotherList = new List<IExample>();
        anotherList.Add(new A());

        FilterList(anotherList);
    }

    static void FilterList(List<IExample> anotherList)
    {
        Type t = anotherList.ElementAt(0).GetType();

        // This does not work:
        //exampleList.OfType<t>().ToList();

        // This does work:
        List<IExample> filteredList = exampleList.Where(item => item.GetType() == t).ToList();

        // The filtered List is then used for further processing ...
    }
}


interface IExample {}
class A : IExample {}
class B : IExample {}

Upvotes: 2

Views: 2016

Answers (1)

Attila Karoly
Attila Karoly

Reputation: 1031

The following fragment seems to anwser the original question:

interface IA {}
class B : IA {}
class C : IA {}

var myList = new List<IA>{new B(), new C()};
var myType = myList[0].GetType();
var myFilteredList = myList.Where(elt => elt.GetType().Equals(myType)).ToList<IA>(); 

Upvotes: 1

Related Questions