[英]Getting the count of most repeated records in Linq
我正在開發一個應用程序,其中必須將歌曲的播放歷史記錄存儲在數據表中。 我有一個名為PlayHistory的表,該表有四列。
Id | SoundRecordingId(FK) | UserId(FK) | DateTime
現在,我必須實現一個查詢,該查詢將返回處於流行階段(即主要播放)的歌曲。 我在sql服務器中編寫了以下查詢,該查詢以某種方式返回我的數據,使其更接近我想要的數據。
select COUNT(*) as High,SoundRecordingId
from PlayHistory
where DateTime >= GETDATE()-30
group by SoundRecordingId
Having COUNT(*) > 1
order by SoundRecordingId desc
它返回了以下數據:
High SoundRecordingId
2 5
2 3
這意味着編號為5和3的歌曲的播放次數最多。ie2如何在C#中通過Linq實現此功能。 到目前為止,我已經做到了:
DateTime d = DateTime.Now;
var monthBefore = d.AddMonths(-1);
var list =
_db.PlayHistories
.OrderByDescending(x=>x.SoundRecordingId)
.Where(t => t.DateTime >= monthBefore)
.GroupBy(x=>x.SoundRecordingId)
.Take(20)
.ToList();
它返回我整個表的列表,其中包含SoundRecording對象的數量,但我只想計數最重復的記錄。 謝謝
我喜歡'linq'語法,它類似於SQL
var query = from history in _db.PlayHistories
where history.DateTime >= monthBefore
group history by history.SoundRecordingId into historyGroup
where historyGroup.Count() > 1
orderby historyGroup.Key
select new { High = historyGroup.Count(), SoundRecordingId = historyGroup.Key };
var data = query.Take(20).ToList();
.GroupBy
方法的重載將解決您的問題。
DateTime d = DateTime.Now;
var monthBefore = d.AddMonths(-1);
var list =
_db.PlayHistories
.OrderByDescending(x=>x.SoundRecordingId)
.Where(t => t.DateTime >= monthBefore)
.GroupBy(x=>x.SoundRecordingId, (key,values) => new {SoundRecordingID=key, High=values.count()})
.Take(20)
.ToList();
我只是將結果選擇器添加到此處的GroupBy
方法調用中,該選擇器執行與您在SQL中編寫的轉換相同的轉換。
有問題的方法重載記錄在這里
為了進一步解決您的問題,您可能需要執行另一個OrderByDescending
以使受歡迎程度順序得到結果。 為了匹配SQL語句,您還必須僅過濾計數> 1。
DateTime d = DateTime.Now;
var monthBefore = d.AddMonths(-1);
var list =
_db.PlayHistories
.Where(t => t.DateTime >= monthBefore)
.GroupBy(x=>x.SoundRecordingId, (key,values) => new {SoundRecordingID=key, High=values.count()})
.Where(x=>x.High>1)
.OrderByDescending(x=>x.High)
.ToList();
大功告成。 只需按計數順序排序列表,然后選擇第一個即可:
var max =
_db.PlayHistories
.OrderByDescending(x=>x.SoundRecordingId)
.Where(t => t.DateTime >= monthBefore)
.GroupBy(x=>x.SoundRecordingId)
.OrderByDescending(x => x.Count())
.First();
這為您提供了一個鍵-值對,其中“ Key
是您的SoundRecordingId
而“值”是其在輸入列表中的出現次數。
編輯:要獲取具有該金額的所有記錄,請選擇此代替:
var grouped =
_db.PlayHistories
.OrderByDescending(x => x.SoundRecordingId)
.Where(t => t.DateTime >= monthBefore)
.GroupBy(x => x.SoundRecordingId)
.Select(x => new { Id = x.Key, Count = x.Count() }
.OrderByDescending(x => x.Count)
.ToList();
var maxCount = grouped.First().Count;
var result = grouped.Where(x => x.Count == maxCount);
通過為您提供所需的內容,可以解決問題。 在LINQ中查詢,僅返回播放計數。
var list = _db.PlayHistories.Where(x => x.DateTimeProp > (DateTime.Now).AddMonths(-1))
.OrderByDescending(y => y.SoundRecordingId.Count())
.ThenBy(z => z.SoundRecordingId)
.Select(xx => xx.SoundRecordingId).Take(20).ToList();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.