Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8323653
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 8, 20262026-06-08T23:47:00+00:00 2026-06-08T23:47:00+00:00

Is there any easy way to query a heterogeneous collection, where the objects in

  • 0

Is there any easy way to query a heterogeneous collection, where the objects in the collection all derive from the same base class but some may be of one derived type and some may be of another?

For example, here’s a class hierarchy:

public class Ship
{
    public string Name { get; set; }
    public string Description { get; set; }
}

public class SailingVessel : Ship
{
    public string Rig { get; set; }
    public int NumberOfMasts { get; set; }
}

public class MotorVessel : Ship
{
    public string Propulsion { get; set; }
    public decimal TopSpeed { get; set; }
}

And here’s an XML document I want to query:

<?xml version="1.0" ?>
<ships xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <ship xsi:type="sailingVessel">
    <name>Cutty Sark</name>
    <description>Tea clipper</description>
    <rig>Ship</rig>
    <numberOfMasts>3</numberOfMasts>
  </ship>
  <ship xsi:type="sailingVessel">
    <name>Peking</name>
    <description>Windjammer of the Flying P Line</description>
    <rig>Barque</rig>
    <numberOfMasts>4</numberOfMasts>
  </ship>
  <ship xsi:type="motorVessel">
    <name>HMS Hood</name>
    <description>Last British battlecruiser</description>
    <propulsion>SteamTurbine</propulsion>
    <topSpeed>28</topSpeed>
  </ship>
  <ship xsi:type="motorVessel">
    <name>RMS Queen Mary 2</name>
    <description>Last transatlantic passenger liner</description>
    <propulsion>IntegratedElectricPropulsion</propulsion>
    <topSpeed>30</topSpeed>
  </ship>
  <ship xsi:type="motorVessel">
    <name>USS Enterprise</name>
    <description>First nuclear-powered aircraft carrier</description>
    <propulsion>Nuclear</propulsion>
    <topSpeed>33.6</topSpeed>
  </ship>
</ships>

I can query the XML document and read its contents into a list of Ship objects:

        XDocument xmlDocument = XDocument.Load("Ships.xml")
        XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";

        var records = (from record in xmlDocument.Descendants("ship")
                       let type = record.Attribute(xsi + "type").Value                         
                       select new Ship
                       {
                           Name = (string)record.Element("name"),
                           Description = (string)record.Element("description")
                       }).ToArray<Ship>();

This returns the following:

Ship[0] (type: Ship):
    Name: Cutty Sark
    Description: Tea clipper
Ship[1] (type: Ship):
    Name: Peking
    Description: Windjammer of the Flying P Line
Ship[2] (type: Ship):
    Name: HMS Hood
    Description: Last British battlecruiser
Ship[3] (type: Ship):
    Name: RMS Queen Mary 2
    Description: Last transatlantic passenger liner
Ship[4] (type: Ship):
    Name: USS Enterprise
    Description: First nuclear-powered aircraft carrier

What I would really like to be able to produce, though, is this:

Ship[0] (type: SailingVessel):
    Name: Cutty Sark
    Description: Tea clipper
    Rig: Ship
    NumberOfMasts: 3
Ship[1] (type: SailingVessel):
    Name: Peking
    Description: Windjammer of the Flying P Line
    Rig: Barque
    NumberOfMasts: 4
Ship[2] (type: MotorVessel):
    Name: HMS Hood
    Description: Last British battlecruiser
    Propulsion: SteamTurbine
    TopSpeed: 28
Ship[3] (type: MotorVessel):
    Name: RMS Queen Mary 2
    Description: Last transatlantic passenger liner
    Propulsion: IntegratedElectricPropulsion
    TopSpeed: 30
Ship[4] (type: MotorVessel):
    Name: USS Enterprise
    Description: First nuclear-powered aircraft carrier
    Propulsion: Nuclear
    TopSpeed: 33.6

How can I modify the LINQ query to intialize a SailingVessel object or a MotorVessel object as appropriate, instead of a base Ship object?

Do I have to do two selects, and duplicate the object initialization for the base class properties (Name and Description) in each one? That is all I can think of but I hate the duplication of code involved. Alternatively, is there some way to initialize the properties for the base class and optionally initialize additional properties for a SailingVessel (Rig, NumberOfMasts) or a MotorVessel (Propulsion, TopSpeed) as appropriate?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-08T23:47:03+00:00Added an answer on June 8, 2026 at 11:47 pm

    Personally I would give each type a static FromXElement method (or constructor), and then create a Dictionary<string, Func<Ship>> like this:

    var factories = new Dictionary<string, Func<Ship>>
    {
         { "sailingVessel", SailingVessel.FromXElement },
         { "motorVessl", MotorVessel.FromXElement },
         ...
    };
    

    Then your query would be:

    var records = from record in xmlDocument.Descendants("ship")
                  let type = record.Attribute(xsi + "type").Value 
                  select factories[type](record);
    

    You could give the Ship class a protected constructor taking XElement to extract the common properties, leaving something like:

    public class SailingVessel : Ship
    {
        public Rig Rig { get; set; }
        public int NumberOfMasts { get; set; }
    
        private SailingVessel(XElement element) : base(element)
        {
            Rig = (Rig) Enum.Parse(typeof(Rig), (string) element.Element("Rig"));
            NumberOfMasts = (int) element.Element("NumberOfMasts");
        }
    
        // Don't really need this of course - could put constructor calls
        // into your factory instead. I like the flexibility of factory 
        // methods though, e.g. for caching etc.
        public static FromXElement(element)
        {
            return new SailingVessel(element);
        }
    }
    

    There will certainly be a fair amount of code involved, but it will all be reasonably simple, and also easy to test.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Is there any easy way to change the color of the UITableViewCellAccessoryCheckmark from standard
Is there any easy way using the api to get a count of all
Is there any easy way to query a stored procedure (Oracle - PL/SQL) for
Is there any easy way to return single scalar or default value if query
Is there any easy way to automatically deploy a web service / java web
Is there any easy way to tell perl now ignore everything that is printed?
Is there any EASY way to sort an array in descending order like how
Is there any easy way to do so?
is there any easy way in the iPhone SDK to include search bars like
Is there any easy way to calculate the number of lines changed between two

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.