1. 程式人生 > >Linq分組及排序,取前N條記錄

Linq分組及排序,取前N條記錄

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 });
            }
        }
    }