I have a database of books.
我有一个书籍数据库。
ID TimesRead
1 45
2 12
3 84
4 1
5 17
6 65
7 4
8 98
9 42
10 14
How do i get the 5 most read books trough linq ?
如何通过linq获得5本最多的阅读书籍?
In this case it would be id= 8,3,6,1,9
.
在这种情况下,它将是id = 8,3,6,1,9。
3 个解决方案
#1
1
from m in MyTable
orderby TimesRead descending
take 5
select m
Or
要么
Mytable.OrderByDesc(x => x.TimesRead).take(5);
#2
1
User ta.speot.is placed a very smart remark: what about ties? Or, what if book #10 also had 42 reads (like 9). It wouldn't be fair to drop it out of the league, would it? In its most extreme form, what if all books had the same amount of reads?
用户ta.speot.is发表了一个非常明智的评论:关系怎么样?或者,如果书#10也有42个读数(如9),该怎么办?放弃联盟是不公平的,不是吗?在最极端的形式,如果所有书籍具有相同的读取量,该怎么办?
Let's assume it's the five highest reads you're interested in. Then you should group by TimesRead
and report the five highest groups with their books (any number):
让我们假设它是你感兴趣的五个最高读数。那么你应该按照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);
this will give you an output like
这会给你一个输出
98 8
84 3
65 6
45 1
42 9
but if 10 also had 42 reads:
但如果10也有42个读数:
98 8
84 3
65 6
45 1
42 9, 10
and if all had the same # reads:
如果所有人都有相同的#read:
42 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
#3
0
Use OrderByDescending() and Take() extension methods for IEnumerable/IQueryable results you get from DB, then use Select() to get only fields you need
使用OrderByDescending()和Take()扩展方法获取从DB获得的IEnumerable / IQueryable结果,然后使用Select()获取您需要的字段
#1
1
from m in MyTable
orderby TimesRead descending
take 5
select m
Or
要么
Mytable.OrderByDesc(x => x.TimesRead).take(5);
#2
1
User ta.speot.is placed a very smart remark: what about ties? Or, what if book #10 also had 42 reads (like 9). It wouldn't be fair to drop it out of the league, would it? In its most extreme form, what if all books had the same amount of reads?
用户ta.speot.is发表了一个非常明智的评论:关系怎么样?或者,如果书#10也有42个读数(如9),该怎么办?放弃联盟是不公平的,不是吗?在最极端的形式,如果所有书籍具有相同的读取量,该怎么办?
Let's assume it's the five highest reads you're interested in. Then you should group by TimesRead
and report the five highest groups with their books (any number):
让我们假设它是你感兴趣的五个最高读数。那么你应该按照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);
this will give you an output like
这会给你一个输出
98 8
84 3
65 6
45 1
42 9
but if 10 also had 42 reads:
但如果10也有42个读数:
98 8
84 3
65 6
45 1
42 9, 10
and if all had the same # reads:
如果所有人都有相同的#read:
42 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
#3
0
Use OrderByDescending() and Take() extension methods for IEnumerable/IQueryable results you get from DB, then use Select() to get only fields you need
使用OrderByDescending()和Take()扩展方法获取从DB获得的IEnumerable / IQueryable结果,然后使用Select()获取您需要的字段