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);
}
If you want to rearrange or sort the elements of the given sequence or collection in descending order in query syntax, then use descending keyword as shown in below example. And in method syntax, use OrderByDescending () method to sort the elements of the given sequence or collection.
LINQ includes five sorting operators: OrderBy, OrderByDescending, ThenBy, ThenByDescending and Reverse. LINQ query syntax does not support OrderByDescending, ThenBy, ThenByDescending and Reverse. It only supports 'Order By' clause with 'ascending' and 'descending' sorting direction.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With