Vivendi
Vivendi

Reputation: 21057

Put items in List with Linq query

I'm getting items from an XML document that looks like this:

<Pages>
  <Page1>
    <item name="name1" />
    <item name="name2" />
  </Page1>
  <Page2>
    <item name="name1" />
    <item name="name2" />
  </Page2>
</Pages>

I want to store this in a list. So i have a Dictionary which should store a list of items.

private Dictionary<string, List<ItemElement>> _pages = new Dictionary<string, List<ItemElement>>();

Then i try to read the XML like this, but how do i add the items to the List? This isn't working:

_pages = Configuration.Elements("Pages").Elements()
    .ToDictionary(x => x.Name.LocalName,
        x => x.Descendants("item")
            .ToList(y => 
                new ItemElement
                {
                    Name = y.Attribute("name").Value,
                    Value = "Value",
                    Origin = "Origin"
                })
            );

But it says: ToList takes '0' arguments. SO how do i solve this issue? How can i add items to the list in this linq query?

Upvotes: 0

Views: 96

Answers (1)

nphx
nphx

Reputation: 1427

Create the ItemElements first, then put them in a list.

_pages = Configuration.Elements("Pages").Elements()
    .ToDictionary(x => x.Name.LocalName,
        x => x.Descendants("item")
            .Select(y => 
                new ItemElement
                {
                    Name = y.Attribute("name").Value,
                    Value = "Value",
                    Origin = "Origin"
                })
            )
            .ToList();

Upvotes: 3

Related Questions