How to filter all variants of the general type using OfType <>

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

I have the following definitions:

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

My list contains all ISeries types, but now I want to get only those ITraceSeries objects, regardless of their actual typical type parameter, for example:

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

How can i do this?

An unfavorable solution would be to introduce the ITraceSeries type, which inherits from ISeries :

 public interface ITraceSeries<T> : ITraceSeries 

Then use ITraceSeries as a filter. But in reality, this does not add new information, but only makes the inheritance chain more complex.

It seems to me that this is a common problem, but I did not find useful information about SO or on the Internet. Thanks for the help!

+6
source share
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<>)))); 
+5
source
 from s in series where s.GetType().GetGenericTypeDefinition()==typeof(ITraceSeries<>) select s; 
+1
source

Source: https://habr.com/ru/post/888635/


All Articles