C#LINQ GroupBy NULL值

时间:2017-08-25 19:55:05

标签: c# linq linq-to-sql

我有一个枚举

public enum Status { New, InProgress, Processed, InComplete};

我正在使用LINQ但在数据库中进行分组。我的问题是我有NULL值代表新状态。那么可以将我的NULL值更新为0吗?然后我的groupby将返回新状态的计数。

这是我的问题:

var results = DbContext.Orders
                       .Where(i => i.Id== Id)
                       .GroupBy(row => new { row.Status})
                       .Select(g => new Stats()
                       {
                           Status = g.Key.Status,
                           Count = g.Count()
                       }).ToList();

2 个答案:

答案 0 :(得分:2)

row.Status的{​​{1}}上使用Null Coalescing运算符,与GroupBy中一样。

答案 1 :(得分:1)

可能看起来像这样:

var results = DbContext.Orders
                       .Where(i => i.Id == Id)
                       .GroupBy(row => row.Status ?? 0) //why are you creating an anonymous class here?
                       .Select(g => new Stats()
                       {
                           Status = (Status)g.Key, //change it like that if it's the enum type
                           Count = g.Count()
                       }).ToList();