简体   繁体   中英

Linq to XML Order by descending?

I am having trouble with the OrderByDescending. It does not sort it correctly. I have an XML file that looks like this:

  <player id="3">
     <name>David, Backham</name>      
     <goals>155</goals>        
  </player>

I am trying to display 3 players with the highest amount of goals.

 XDocument doc = XDocument.Load("players.xml");

                                     /// .OrderByDescending(r => r.Attribute("goals"))
        var players = from r in doc.Descendants("player").OrderByDescending(r => r.Value)

                           select new
                           {
                               Name = r.Element("name").Value + "   ",
                               Goal = r.Element("goals").Value + "    ",

                           };


        foreach (var r in players)
        {              
            Console.WriteLine(r.Name + r.Goal);
        }

Perhaps like this:

var players = 
    (from r in doc.Descendants("player")
     orderby int.Parse(r.Element("goals").Value) descending 
     select new
     {
         Name = r.Element("name").Value + "   ",
         Goal = r.Element("goals").Value + "    ",
     })
    .Take(3);

Or in fluent syntax:

var players = doc.Descendants("player")
                 .OrderByDescending(r => int.Parse(r.Element("goals").Value))
                 .Select(r => new
                  {
                      Name = r.Element("name").Value + "   ",
                      Goal = r.Element("goals").Value + "    ",
                  })
                 .Take(3);

Note that you'll need to parse the string value to an integer to get the correct sort order.

To filter the results, you can just do this:

var players = 
    (from r in doc.Descendants("player")
     where r.Element("name").Value.StartsWith("David")
     orderby int.Parse(r.Element("goals").Value) descending 
     select new
     {
         Name = r.Element("name").Value + "   ",
         Goal = r.Element("goals").Value + "    ",
     })
    .Take(3);

Or in fluent syntax:

var players = doc.Descendants("player")
                 .Where(r => r.Element("name").Value.StartsWith("David"))
                 .OrderByDescending(r => int.Parse(r.Element("goals").Value))
                 .Select(r => new
                  {
                      Name = r.Element("name").Value + "   ",
                      Goal = r.Element("goals").Value + "    ",
                  })
                 .Take(3);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM