2

I've tried to sort my xml file by attribute's value with no luck.

data.Descendants("person").OrderBy(x => x.Attribute("id").Value);

data contains:

<persons>
  <person id="1">
    <name>Abra</name>
    <age>25</age>
  </person>
  <person id="2">
    <name>Cadabra</name>
    <age>29</age>
  </person>
  <person id="4">
    <name>Hokus</name>
    <age>40</age>
  </person>
  <person id="3">
    <name>Pokus</name>
    <age>30</age>
  </person>
</persons>

Answer given here does not work for me.

I'm using MVS 2010 for Windows Phone 7.

I would be grateful for any help.

--

Update

Thank You for quick responses!

juharr asked a good question... i was expecting that OrderBy would modify data. Now i know i was wrong.

I want to modify data and i've done as follows (thanks Matt Lacey):

var people = data.Elements("person").OrderBy(p => (string)p.Attribute("id"));

    data.Descendants("person").Remove();
    data.Element("persons").Add(people);

but i still got nothing. Data is empty, it contains only <persons />

I wonder what's wrong now.


I manage to solve my problem by using this code:

    XDocument datatemp = new XDocument(data);

    var people = datatemp.Descendants("person").OrderBy(x => (int)int.Parse(x.Attribute("id").Value));

    data.Descendants("person").Remove();
    data.Element("persons").Add(people);

Is any other way (more elegant) to modify data using OrderBy instead of creating datatemp?

3
  • 1
    Can you be more specific about "no luck"? Commented Jan 5, 2011 at 12:47
  • 2
    Are you capturing the result of the OrderBy or are you expecting it to modify data? Commented Jan 5, 2011 at 13:24
  • I know this is an ancient question. But you avoid the datatemp variable by adding .ToList() or .ToArray() as Dima said. stuff.OrderBy(...).ToList() prevents your IEnumerable to be empty when adding to persons. Commented Apr 2, 2014 at 16:48

2 Answers 2

1

Based on the question you linked to, this works:

var people = from p in data.Elements("person")
             orderby (string)p.Attribute("id")
             select p;

or

var people = data.Elements("person").OrderBy(p => (string)p.Attribute("id"));

(tested on a phone to confirm too.)

Sign up to request clarification or add additional context in comments.

1 Comment

this will be sorted by string.sort of int.sort?
1

I hope this helps you

var people = data.Elements("person").OrderBy(p => (string)p.Attribute("id")).ToArray();

data.Descendants("person").Remove();
data.Element("persons").Add(people);

Don't forget to use the ToArray() method for your people.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.