Question

Is it possible to use a lambda expression inside an object initialization expression? Please look at the code below:

XDocument doc = new XDocument(
    new XDeclaration("1.0", "utf-8", "yes"),
        new XElement("data",
            new XElement("album",
                new XElement("slide1"),
                new XElement("slide2"),
                new XElement("slide3")
                )
            )
        );

instead of...

new XElement("slide1"),
new XElement("slide2"),
new XElement("slide3")

...I want to use a lamda expression which returns XElement[]

Was it helpful?

Solution

Func<XElement[]> elementCreatorFunc = 
    () => new[] { new XElement(...), new XElement(...) };

XDocument doc = new XDocument(
    new XDeclaration("1.0", "utf-8", "yes"),
        new XElement("data",
            new XElement("album",
                elementCreatorFunc()
                )
            )
        );

OTHER TIPS

The following is the final solution. So instead of an external function I am doing it inline:

XDocument doc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), 
    new XElement("data", 
        new XElement("album",
            (from item in Model.Items
             select new XElement("slide",
                         new XAttribute("title", item.title)))

        )
    )
);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top