[英]How to get the 5 highest values trough linq
我有一個書籍數據庫。
ID TimesRead
1 45
2 12
3 84
4 1
5 17
6 65
7 4
8 98
9 42
10 14
如何通過linq獲得5本最多的閱讀書籍?
在這種情況下,它將是id= 8,3,6,1,9
。
from m in MyTable
orderby TimesRead descending
take 5
select m
要么
Mytable.OrderByDesc(x => x.TimesRead).take(5);
用戶ta.speot.is發表了一個非常明智的評論:關系怎么樣? 或者,如果書#10也有42個讀數(如9),該怎么辦? 放棄聯盟是不公平的,不是嗎? 在最極端的形式,如果所有書籍的讀取數量相同,該怎么辦?
讓我們假設它是你感興趣的五個最高讀數 。那么你應該TimesRead
分組,並用他們的書(任何數字)報告五個最高的組:
var readGroups = from b in books
group b by b.TimesRead into readgroup
select new
{
TimesRead = readgroup.Key,
Books = string.Join(", ", readgroup.Select(b => b.Id))
};
var highFive = readGroups.Take(5);
這會給你一個輸出
98 8
84 3
65 6
45 1
42 9
但如果10也有42個讀數:
98 8
84 3
65 6
45 1
42 9, 10
如果所有人都有相同的#read:
42 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
對從DB獲取的IEnumerable / IQueryable結果使用OrderByDescending()和Take()擴展方法,然后使用Select()僅獲取所需的字段
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.