Linq to xml, retreaving generic interface-based list
- by Rita
I have an xml document that looks like this
<Elements>
<Element>
<DisplayName />
<Type />
</Element>
</Elements>
I have an interface,
interface IElement
{
string DisplayName {get;}
}
and a couple of derived classes:
public class AElement: IElement
public class BElement: IElement
What I want to do, is to write the most efficient query to iterate through the xml and create a list of IElement, containing AElement or BElement, based on the 'Type' property in the xml.
So far I have this:
IEnumerable<AElement> elements =
from xmlElement in XElement.Load(path).Elements("Element")
where xmlElement.Element("type").Value == "AElement"
select new AElement(xmlElement.Element("DisplayName").Value);
return elements.Cast<IElement>().ToList();
But this is only for AElement, is there a way to add BElement in the same query, and also make it generic IEnumerable? Or would I have to run this query once for each derived type?