Linq多字段分组排序并取前N条记录时,一定要先分组再排序,不然取到的记录是不规则的
代码示例【按HotWord分组,并取sorNum倒序,取前15条记录】
[Route("api/XXX/getHotWord")]
public HttpResponseMessage Post(WordModel model)
{
try
{
using (BZTEntities ctx = new BZTEntities())
{
var wflist = from u in ctx.T_HotWord
where u.Type==model.type
group u by new { HotWord = u.HotWord, sortNum = u.SortNum } into g
select new { g.Key.HotWord, g.Key.sortNum };
wflist = wflist.OrderByDescending(x => x.sortNum);
var hotWord = wflist.ToList().Take(15).Select(a => a.HotWord).ToList();
var Str = string.Join(",", hotWord);
return Request.CreateResponse(HttpStatusCode.OK, new { errorCode = 1, hotWord = Str });
}
}
catch (Exception ex)
{
Log.Error("获取xxxxx失败:" + ex.Message, ex);
return Request.CreateResponse(HttpStatusCode.OK, new { errorCode = 2 });
}
}
}