tags:

views:

106

answers:

2

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[]

Thanks for help!

A: 
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()
                )
            )
        );
Ben M
Thank you very much. Your answer was exactly the right answer to my question. However I wanted to have something slightly different and your answer guided me into the right direction. See solution below.Thank you very much again.
Joris
Glad to help!
Ben M
A: 

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)))

        )
    )
);
Joris