简体   繁体   English

在Entity Framework或LINQ中进行选择时,如何将日期列分组为较不精确的格式?

[英]How can I group a date column to a less precise format while selecting in Entity Framework or LINQ?

I am collecting data within every ten seconds ( six records in a minute ). 我每ten seconds收集一次数据(一minute six records )。 Using Entity Framework or LINQ , I want to obtain the average of the records within a every minute. 我想使用Entity FrameworkLINQ来获取每分钟内记录的平均值。
Simply, Date column is in ( %Y.%m.%d %H:%i:%s ) format, and i want to group by ( %Y.%m.%d %H:%i ) format in mysql using Entity Framework or LINQ 简而言之,“日期”列为( %Y.%m.%d %H:%i:%s )格式,我想按mysql%Y.%m.%d %H:%i )格式分组使用Entity FrameworkLINQ

Assuming that you mean you have a date time column you can group by the DateTime properties Year , Month , Day , Hour , and Minute . 假设您有日期时间列,则可以按DateTime属性YearMonthDayHourMinute进行分组。

var results = from row in db.SomeTable
              group by new 
              { 
                  row.Date.Year, 
                  row.Date.Month, 
                  row.Date.Day, 
                  row.Date.Hour, 
                  row.Date.Minute 
              } into grp
              select new 
              { 
                  YMDHM = grp.Key
                  SomeAverage = grp.Average(x => x.SomeValueToAverage)
              };

Then when you iterate the results you can turn the values in YMDHM back into a DateTime . 然后,当您迭代结果时,可以将YMDHM的值重新转换为DateTime Here's an example where you could turn the results into a Dictionary . 这是一个示例,您可以将结果转换为Dictionary

var dictionaryOfAverages = results.ToDictionary(
    x => new DateTime(x.YMDHM.Year, 
                      x.YMDHM.Month,  
                      x.YMDHM.Day,  
                      x.YMDHM.Hour,  
                      x.YMDHM.Minute,  
                      0), 
    x => x.SomeAverage);

On the other hand if you actually mean you are storing the date time in the DB as a formatted string then the following would be what you want 另一方面,如果您实际上是要将日期时间作为格式化字符串存储在数据库中,则需要以下内容

var results = from row in db.SomeTable
              group by new row.Date.SubString(0, 16) into grp
              select new 
              { 
                  YMDHM = grp.Key
                  SomeAverage = grp.Average(x => x.SomeValueToAverage)
              };

This is assuming that your string formatted dates look like "2013.05.08 07:25:33" If the format isn't fixed width with leading zeros for month, day, and/or hour you'd have to do something like row.Date.SubString(0, row.Date.Length - 3) instead 假设您的字符串格式日期看起来像“ 2013.05.08 07:25:33”。如果格式不是固定的宽度,并且月,日和/或小时的前导零,则必须执行类似于row.Date.SubString(0, row.Date.Length - 3)代替

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM