如何在 Linq to sql 中通过语句获取组中的唯一日期

How to get only date in group by statement in Linq to sql

如何在 LINQ 中通过语句获取组中的唯一日期

 var res = query.GroupBy(   b => b.CreatedDate.ToString() ).Select(c => new
                {
                    ShredQueueCount = c.Sum(w => w.ShredQueueCount),
                    ShredCompletedCount = c.Sum(w => w.ShredCompletedCount),
                    ShredValFailureCount = c.Sum(w => w.ShredValFailureCount),
                    ShredExceptionCount = c.Sum(w => w.ShredExceptionCount),
                    CreatedDate = c.Select(w => w.CreatedDate)
                });

如果它是 LINQ 将在 SQL 服务器端使用到 SQL 的 LINQ 表达式,那么您需要 EntityFunctions.TruncateTime 如:

query.GroupBy(b => EntityFunctions.TruncateTime(b.CreatedDate.Date))

否则,对于 LINQ to objects,您可以使用:

query.GroupBy(b => b.CreatedDate.Date)

如果你的字段是Nullable<DateTime>类型那么你可以这样做:

query.GroupBy(b => b.CreatedDate.DefaultIfEmpty().Date)

这将忽略 DateTime 字段中的 Time 部分。