将Linq groupby count映射到C#实体

本文关键字:实体 映射 count Linq groupby | 更新日期: 2023-09-27 17:59:02

我有一个sql查询,它在单个字段上执行groupby。然后它计算groupby的。到目前为止还不错。

select type, count(*) 
from myTable
group by type
//Result    
//TypeA = 5
//TypeB = 3

然而,我在使用Linq执行此查询时遇到了问题,因为我需要将Count()的结果映射到特定实体。

我想将计数映射到的实体:

public class MyEtity(){
    public int TypeACount {get; set;}
    public int TypeBCount {get; set;}
}

我当前使用的linq查询是哪个

MyEntity test = data
    .GroupBy(c => c.type)
    .Select(g => new MyEntity (){
        TypeACount = g.Where(d => d.type == "A").Count(),
        TypeBCount = g.Where(d => d.type == "B").Count()
    });

额外信息

根据一些答案,一些额外的信息。我最初的计划是使用以下内容。

var firstResults = session.Query<MyEntity>()
    .Where(//several date filter conditions)
    .ToList();
return new MyEntity() {
    TypeACount = firstResults.Where(s => s.type == "A").Count(),
    TypeBCount = firstResults.Where(s => s.type == "B").Count()
};

这是可行的,但查询的表相当大,而且查询需要相当长的时间。根据同事的反馈,有人问我是否不能将查询分成1部分,而不是将其分离。想法是查询计数逻辑将保留在SQL中,而不是C#中。我不知道这是否真的会更快,但这正是我试图弄清楚的。

将Linq groupby count映射到C#实体

您应该在获得信息后进行映射

var results = data
    .Where(c => c.TypeOfUsage == "A" || c.TypeOfUsage == "B")
    .GroupBy(c => c.TypeOfUsage)
    .Select(g => new 
    {
        Type = g.Key,
        Count = g.Count()
    }).ToList();
MyEntity test = new MyEntity
{
    TypeACount = results.FirstOrDefault(d => d.Type == "A")?.Count ?? 0,
    TypeBCount = results.FirstOrDefault(d => d.Type == "B")?.Count ?? 0
}

或者如果你没有C#6

var a = results.FirstOrDefault(d => d.Type == "A");
var b = results.FirstOrDefault(d => d.Type == "B");
MyEntity test = new MyEntity
{
    TypeACount = a == null ? 0 : a.Count,
    TypeBCount = b == null ? 0 : b.Count
}

另一种选择是使用常数组。

MyEntity test= data
    .Where(c => c.TypeOfUsage == "A" || c.TypeOfUsage == "B")
    .GroupBy(c => 1)
    .Select(g => new MyEntity 
    {
        TypeACount = g.Where(d => d.TypeOfUsage == "A").Count(),
        TypeBCount = g.Where(d => d.TypeOfUsage == "B").Count()
    }).Single();

这更像下面的SQL

select 
    sum(case when typeOfUseage = 'A' then 1 else 0 end) AS TypeACount
    , sum(case when typeOfUseage = 'B' then 1 else 0 end) AS TypeBCount
from myTable

为什么不采用分类方式?,我在您的查询中没有看到分组依据或选择的原因;

            var entity=new MyEntity()
            entity.TypeACount = data.Count(a => a.TypeOfUsage == "A"),
            entity.TypeBCount =data.Count(b => b.TypeOfUsage == "B")