Entity Framework linq 和按计数分组

Entity Framework linq and group by count

这是我现在的 table。我试图找到 NotificatinsID 不为空的行并获取它们的计数。预期结果和class如下。

ID  UserCreated NotificationsID
1      Test          89
2      Test1         NULL
3      Test2         NULL
4      Test3         91
4      Test4         92
4      Test5         93
5      Test6         94
5      Test7         95

public class DataModel
{
    public int ID { get; set; }
    public String UserCreated { get; set; }
    public int? NotificatinsID { get; set; }
}

预期结果

ID   NotificationsCount
1        1
2        0
3        0
4        3
5        2

您可以使用以下内容:

var result = models.GroupBy(m => m.ID)
    .Select(g => new { g.Key, NotificationsCount = g
            .Where(m => m.NotificatinsID.HasValue).Count() }).ToList();

我们使用 GroupBy 按 ID 对项目进行分组,然后检查 .NotificatinsID.HasValue 以仅计算 NotificatinsID 属性 不为空的项目。