Reputation: 135
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);
}
Upvotes: 5
Views: 9143
Reputation: 148980
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);
Upvotes: 8