Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Short way to achieve dynamic objects from LINQ to XML select query?

Is there an initialization syntax to the ExpandoObject that I can use to my advantage in a LINQ to XML query for brevity purposes?

Note: The results of the query are intended to be passed outside the scope of the current assembly so anonymous types are out of the question (see why here).

I'm trying to use brief syntax like the following to create dynamic/expando objects:

public IEnumerable<dynamic> ParseUserXml(string strXmlUser) {

var qClients =
    from client in xdoc.Root.Element(XKey.clients).Elements(XKey.client)
    // client object

    // I cannot get ExpandoObject to initialize inline 
    select new ExpandoObject() {     // try initialization syntax, COMPILE ERR
        OnlineDetails = new
        {
            Password = client.Element(XKey.onlineDetails).
                Element(XKey.password).Value,
            Roles = client.Element(XKey.onlineDetails).
                Element(XKey.roles).Elements(XKey.roleId).
                Select(xroleid => xroleid.Value)
            // More online detail fields TBD
        },

        // etc ....

        // YIELD DYNAMIC OBJECTS BACK THROUGH IEnumerable<dynamic>...
        foreach (var client in qClients)
        {
            yield return client;
        }

More involved solutions to make this code work might be:

  • create concrete class and initialize it instead (but I don't want to create a bunch of those).
  • use anonymous type and copy its members to a dynamic object (somewhat redundant) and return the dynamic objects

Is there an equally short syntax to achieve what I intend to do by the erroneous code in question, or will I have to expand the code base in some manner to get the desired result?

like image 977
John K Avatar asked Nov 14 '22 02:11

John K


1 Answers

Unfortunately I don't think you'll be able to do this. What you can do is create a helper method and call it.

var qClients =
    from client in xdoc.Root.Element(XKey.clients).Elements(XKey.client)
    // client object
    select ClientXmlToExpandoObject(client);

The helper might look something like

public dynamic ClientXmlToExpandoObject(System.Xml.Linq.XElement client)
{
    dynamic result = new ExpandoObject();
    result.OnlineDetails = new
        {
            Password = client.Element(XKey.onlineDetails).
                Element(XKey.password).Value,
            Roles = client.Element(XKey.onlineDetails).
                Element(XKey.roles).Elements(XKey.roleId).
                Select(xroleid => xroleid.Value)
            // More online detail fields TBD
        };
    return result;
}
like image 112
David Ruttka Avatar answered Dec 26 '22 00:12

David Ruttka