我遇到了OrderByDescending的问题。它没有正确排序。 我有一个XML文件,如下所示:
<player id="3">
<name>David, Backham</name>
<goals>155</goals>
</player>
我正在尝试展示3个目标最多的玩家。
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);
}
答案 0 :(得分:5)
也许是这样:
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);
或者用流利的语法:
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);
请注意,您需要将字符串值解析为整数以获得正确的排序顺序。
要过滤结果,您可以这样做:
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);
或者用流利的语法:
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);