How to filter to all variants of a generic type us

2019-02-17 08:11发布

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!

2条回答
一夜七次
2楼-- · 2019-02-17 09:05

You can use reflection to achieve it:

var filteredList = myList.Where(
    x => x.GetType()
          .GetInterfaces()
          .Any(i => i.IsGenericType && (i.GetGenericTypeDefinition() == typeof(ITraceSeries<>))));
查看更多
Anthone
3楼-- · 2019-02-17 09:10
from s in series
where s.GetType().GetGenericTypeDefinition()==typeof(ITraceSeries<>)
select s;
查看更多
登录 后发表回答