【问题标题】:How to get the count of each distinct value in a column using Linq如何使用 Linq 获取列中每个不同值的计数
【发布时间】:2021-11-14 08:12:15
【问题描述】:

我有一张如下图所示的表格

Db Table Example

我尝试的是返回不同的

var result = db.TaskTable.Select(item => item.Status).Distinct().Count();
string json = Newtonsoft.Json.JsonConvert.SerializeObject(result,Newtonsoft.Json.Formatting.Indented);
return Ok(json);

为我的 Web API 使用 Link 我想返回每个的不同计数。例如在 user_goup A 我想将其返回为:

{ “进行中:”“2” “已完成”:“1” “已停止”:“1”}

【问题讨论】:

    标签: c# entity-framework asp.net-core .net-core asp.net-core-webapi


    【解决方案1】:

    从以下内容开始:

    var q = from item db.TaskTable
            group by item.Status into byStatus
            select new {Status = byStatus.Key, Count = byStatus.Distinct().Count() };
    

    然后根据结果手动构造 JSON。

    【讨论】:

    • 您可以使用fluent api .ToDictionary(i => i.Status, i => i.Count) 格式化来自IQuerable 的json 结果。不确定是否有 linq sql 格式。
    猜你喜欢
    • 2011-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-16
    • 2022-01-12
    • 1970-01-01
    • 2016-07-06
    相关资源
    最近更新 更多