Search code examples
c#linqgenericsfilteroftype

How to filter to all variants of a generic type using OfType<>


I want to filter objects in a List<ISeries> using their type, using OfType<>. My problem is, that some objects are of a generic interface type, but they do not have a common inherited interface of their own.

I have the following definitions:

public interface ISeries
public interface ITraceSeries<T> : ISeries
public interface ITimedSeries : ISeries
//and some more...

My list contains all kinds of ISeries, but now I want to get only the ITraceSeries objects, regardless of their actually defined generic type parameter, like so:

var filteredList = myList.OfType<ITraceSeries<?>>(); //invalid argument!

How can I do that?

An unfavored solution would be to introduce a type ITraceSeries that inherits from ISeries:

public interface ITraceSeries<T> : ITraceSeries

Then, use ITraceSeries as filter. But this does not really add new information, but only make the inheritance chain more complicated.

It seems to me like a common problem, but I did not find useful information on SO or the web. Thanks for help!


Solution

  • You can use reflection to achieve it:

    var filteredList = myList.Where(
        x => x.GetType()
              .GetInterfaces()
              .Any(i => i.IsGenericType && (i.GetGenericTypeDefinition() == typeof(ITraceSeries<>))));