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!
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With