0

is there a way to get an object from a collection of a specific subtype when subtype is only known at run time? something like:

class A
{}

class B : A
{}

class C : A
{}

Main()
{ 
  List<A> outsideList = new List<A>() {new A(), new B(), new C()};

     foreach(var ojb in outsideList)
     {
       dosomethingwithanobject(ojb);
     }
}

void dosomethingwithanobject(A obj)
{
     List<A> intenalList = new List<A>() { new C(), new A(), new B()};
   // this can be A, B or C
   type DESIREDTYPE = typeof(obj);

  var item = list.GetSubType<DESIREDTYPE>().FirstOrDefault();

      // do something with the item
}
Yan D
  • 136
  • 2
  • 11
  • Possible duplicate of [How do I use reflection to call a generic method?](https://stackoverflow.com/questions/232535/how-do-i-use-reflection-to-call-a-generic-method) – thehennyy Feb 08 '19 at 07:43

2 Answers2

1

I think you can use the the following code:

var result = intenalList.Where(x => x.GetType() == obj.GetType()).FirstOrDefault();
kapd
  • 639
  • 1
  • 7
  • 20
0

LINQ has two operations for transforming a sequence of unknown (or parent) types to subtypes: Cast and OfType.

Cast applies the type conversion to each element and fails if it is invalid. OfType only returns the elements that can be converted to the new type.

So,

var item = list.OfType<DESIREDTYPE>().FirstOrDefault();
NetMage
  • 26,163
  • 3
  • 34
  • 55
  • thanks NetMage, this is indeed quite useful and i am using it a lot however this scenario implies the DESIREDTYPE is known at compile time (i.e. it expect an actual class name to be placed in the brackets) where as my situation is where the actual type will only be known at run type (potentially inferred from the string of type name or object passed). – Yan D Feb 09 '19 at 08:00
  • Sorry, I didn't notice that (the all caps variable name threw me off :) ). @kapd's answer seems best in that case (though I would use your desired type variable). – NetMage Feb 11 '19 at 18:28