我根据图书的发布时间打印所有最新记录。(PubEnd
)。现在我可以按降序打印所有出版的书籍。
我需要打印20个最新发布的标题。我怎么能这样做? 现在,下面的代码是打印按降序发布的所有书籍。
var query = docs.Descendants(name)
.Select(x => new
{
Title = (string)x.Element(ns + "TITLE"),
Status = (string)x.Element(ns + "STATUS"),
PubEnd = (string)x.Element(ns + "PUB_END")
})
.Select(x => new
{
Title = x.Title,
Status = x.Status,
PubEnd = x.PubEnd,
}).OrderByDescending(x => x.PubEnd).ToList();
foreach (var book in query)
{
if (book.Status == "Published")
{
Response.Write(book.Title);
Response.Write(book.Status);
Response.Write(book.PubEnd);
}
}
答案 0 :(得分:2)
使用Take()
:
foreach (var book in query.Take(20))
{
//print
}
如果总是,则只需要相应地更新查询本身:
(..).OrderByDescending(x => x.PubEnd).Take(20).ToList();
答案 1 :(得分:2)
您应该只需要使用Take(20)
Here is the documentation on Take
您的代码将变为:
...OrderByDescending(x => x.PubEnd).Take(20).ToList()
DISTINCT更新
Here is the documentation for Distinct
你的代码就是这样,我假设你在20岁之前想要分开:)
...OrderByDescending(x => x.PubEnd).Distinct().Take(20).ToList()
答案 2 :(得分:1)
Take(20)
这应该是你需要的:
var list = docs.Descendants(name)
.Select(x => new
{
Title = (string)x.Element(ns + "TITLE"),
Status = (string)x.Element(ns + "STATUS"),
PubEnd = (string)x.Element(ns + "PUB_END")
})
.OrderByDescending(x => x.PubEnd).Take(20).ToList();
如果您想获得截然不同的结果:
var list = (...).OrderByDescending(x => x.PubEnd).Distinct().Take(20).ToList();
答案 3 :(得分:1)
var query = docs.Descendants(name)
.Select(x => new
{
Title = (string)x.Element(ns + "TITLE"),
Status = (string)x.Element(ns + "STATUS"),
PubEnd = (string)x.Element(ns + "PUB_END")
})
.OrderByDescending(x => x.PubEnd).Take(20); // Take will get the first N records.
foreach (var book in query)
{
if (book.Status == "Published")
{
Response.Write(book.Title);
Response.Write(book.Status);
Response.Write(book.PubEnd);
}
}