linq 使用c#返回异步任务列表

wwodge7n  于 2023-02-17  发布在  C#
关注(0)|答案(1)|浏览(154)

我有下面的类和枚举:

public class StatusCount
{
    public string Status { get; set; }
    public int Count { get; set; }
}

public enum myEnum {
    A,
    B,
    C
}

public async Task<List<StatusCount>> GetStatusCount()
{
    var listOfEnums = System.Enum.GetValues(typeof(myEnum)).Cast<myEnum>().ToList();//A,B,C
    var query1 =_dbcontext.Table1.Include().Where().Count();//10
    var query2 =_dbcontext.Table2.Include().Where().Count();//5
    var query2 =_dbcontext.Table3.Include().Where().Count();//15

    return ???
}

我想从GetStatusCount方法输出如下,需要将列表返回到控制器。不确定如何Map/发送状态为“A”的query 1 count值等。

[
    {
        status:A
        count: 10
    },
    {
        status:B
        count: 5
    },
    {
        status:C
        count: 15
    }
]
von4xj4u

von4xj4u1#

可能你需要在这里按常量分组。它将允许使用Count并返回IQueryable

public async Task<List<StatusCount>> GetStatusCount()
{
    var query1 = _dbcontext.Table1.Where(...).GroupBy(x => 1).Select(x => new StatusCount{ Status = "A", Count = g.Count() });
    var query2 = _dbcontext.Table2.Where(...).GroupBy(x => 1).Select(x => new StatusCount{ Status = "B", Count = g.Count() });
    var query3 = _dbcontext.Table3.Where(...).GroupBy(x => 1).Select(x => new StatusCount{ Status = "C", Count = g.Count() });

    return query1.Concat(query2).Concat(query3).ToListAsync();
}

相关问题