如何计算按shortdatestring分组的表的行? [英] How to count rows of a table grouped by shortdatestring?
问题描述
我们有一个具有以下结构的数据库:
We have an database with an this structure:
public partial class ChartData
{
public int Id { get; set; }
public DateTime Timestamp { get; set; }
public string Function { get; set; }
public int Duration { get; set; }
public bool IsError { get; set; }
}
现在,我们要按Timestamp.ToShortDateString()
对数据库的条目进行分组,然后计算属于该日期的条目.
Now we want to group the entries of this database by Timestamp.ToShortDateString()
and then count the entries belonging to this date.
例如,我们有:
2019-06-04 11:54:02,135,someFunction,30,False,
2019-06-04 11:55:03,135,someFunction,230,False,
2019-06-04 11:56:03,150,someFunction,4,True,
2019-06-05 11:54:03,230,someFunction,46,False,
2019-06-05 11:55:03,230,someFunction,46,False,
我想要这个结果:
{date: 2019-06-04, rows: 3}
{date: 2019-06-05, rows: 2}
public List <LogFileDTO> GetLogFilesData()
{
var items = db.ChartDatas.GroupBy(x = > new {
x.Timestamp.ToShortDateString
}).Select(x = > new LogFileDTO {
date = x.Timestamp.First(),
rows = x.Count ?
}).ToList();
}
所以我真的不知道如何按日期对输入内容进行分组,然后对每个组的行进行计数.
So I do not really know how to group this input by date and then count the rows of each group.
推荐答案
您只需要对TimeStamp
的Date
属性进行分组,然后在每个IGropuing
的Key
上使用Select
进行投影.和Count
如下所示:
You simply need to group on the Date
property of the TimeStamp
and then project using Select
on the Key
of each IGropuing
and Count
like below :
var items = db.ChartDatas.GroupBy(x => x.Timestamp.Date) // group only on Date
.Select(x => new LogFileDTO
{
Date = x.Key.ToShortDateString(),
Rows = x.Count()
}).ToList();
Key
将仅包含DateTime
对象的日期部分,而Count()
将说明该日期在组中的行数.
Key
will contain only date part of DateTime
object and Count()
will tell the number of rows for that date in the group.
希望有帮助!
这篇关于如何计算按shortdatestring分组的表的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!