Reputation: 402
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
}
Upvotes: 0
Views: 39
Reputation: 26917
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();
Upvotes: 0
Reputation: 659
I think you can use the the following code:
var result = intenalList.Where(x => x.GetType() == obj.GetType()).FirstOrDefault();
Upvotes: 1