Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 906
Marcel Avatar asked May 20 '11 11:05

Marcel


2 Answers

You can use reflection to achieve it:

var filteredList = myList.Where(
    x => x.GetType()
          .GetInterfaces()
          .Any(i => i.IsGenericType && (i.GetGenericTypeDefinition() == typeof(ITraceSeries<>))));
like image 108
LukeH Avatar answered Sep 22 '22 06:09

LukeH


from s in series
where s.GetType().GetGenericTypeDefinition()==typeof(ITraceSeries<>)
select s;
like image 25
VikciaR Avatar answered Sep 22 '22 06:09

VikciaR