开发者

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 th开发者_运维百科e web. Thanks for help!


You can use reflection to achieve it:

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


from s in series
where s.GetType().GetGenericTypeDefinition()==typeof(ITraceSeries<>)
select s;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜