Is it possible to use LINQ to XML to create an array of a polymorphic type?
I have 3 classes, Base, Der1 and Der2. Base is base class for Der1 and Der2. I have an xml file in which I have nodes corresponding to Der1 and Der2 objets. What I’d like to do is to parse the file and fill in a List with Der1 and Der2 objects.
xml would look like this:
<nodes>
<node type = "Der1" attr1="val1" />
<node type = "Der2" attr2="val2" />
</nodes>
What I tried to do but what does not work is:
List<Base> PMList =
(from der1node from xmlDoc.Descendants("nodes")
where der1node.type == ("Der1")
select new Der1()
{
Attr1 = der1node.Attribute("attr1").Value
}
).Union<Base>
(from der2node from xmlDoc.Descendants("baseNode")
where der2node.type == ("Der2")
select new Der2()
{
Attr2 = der2node.Attribute("attr2").Value
}
).ToList<Base>();
Here what I tried to do is to construct Der1 objects with type=Der1 and Der2 objects with type=Der2 and add them together into a List using Union.
However this does not work. How can I get objects of different type using LINQ to XML and put them in one polymorphic collection?
One way would be to cast the new instances to their base class before projecting them: