簡體   English   中英

幫助Linq表達式根據字段計數返回字符串列表

[英]Help with Linq expression to return a list of strings based on field count

說我有一個表與這些列的評論:Id,Comment,Category,CreatedDate,CommenterId

我想從評論表中獲取前5個類別(基於該表中每個類別的計數)。 我如何在linq中執行此操作,以返回List或IQueryable?

你可以使用這樣的東西:

var query = comments
    .GroupBy(comment => comment.Category)
    .OrderByDescending(g => g.Count())
    .Select(g => g.Key)
    .Take(5);

嘗試這樣的事情:

var topComments = from comment in Comments
                  group comment by comment.Category into grp
                  orderby grp.Count() descending
                  select grp.Key;

var topFive = topComments.Take(5);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM