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:
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?
I ended up using one of Jon Skeet's code answers from a related question. Code sample copied here for posterity. It uses the raw classes rather than query syntax.
// Code answer by Jon Skeet.
var qClients = xdoc.Root
.Element(XKey.clients)
.Elements(XKey.client)
.Select(client => {
dynamic o = new ExpandoObject();
o.OnlineDetails = new ExpandoObject();
o.OnlineDetails.Password = client.Element(XKey.onlineDetails)
.Element(XKey.password).Value;
o.OnlineDetails.Roles = client.Element(XKey.onlineDetails)
.Element(XKey.roles)
.Elements(XKey.roleId)
.Select(xroleid => xroleid.Value);
return o;
});