jeudi 7 février 2019

is there a way to dynamically assign type to a generic linq expression?

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
}





Aucun commentaire:

Enregistrer un commentaire