我有一个枚举
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();
答案 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();