0

I'm trying to do the following:

Type type = someObject.GetType();
if (someCollection.OfType<type>().Any())
{
    // some code
}

And the problem is that OfType<type>() only takes types directly like <T> and you can't pass it as an argument... is there something I can do to achieve the desired result?

NewProger
  • 2,945
  • 9
  • 40
  • 58
  • You can, but you have to do a bit of reflection. – Kirill Bestemyanov Apr 08 '20 at 09:55
  • Why not just `.Any(type.IsInstanceOfType)`? – Sweeper Apr 08 '20 at 09:57
  • Please, refer to this question [C# use System.Type as Generic parameter](https://stackoverflow.com/questions/4667981/c-sharp-use-system-type-as-generic-parameter) – Pavel Anikhouski Apr 08 '20 at 09:57
  • No need for reflection, you can just use `Where(o => type.IsAssignableFrom(o.GetType())` rather than `OfType`. The close duplicate contains more details on that (scroll down past the first answer). – Heinzi Apr 08 '20 at 09:59
  • Thank you guys! The reason why is very simple. Because I have no idea what I'm doing :) I'm still just learning how to use Linq. But your advice worked and I was able to accomplish what I was trying to do. – NewProger Apr 08 '20 at 10:12

0 Answers0