Linq按日期获得数据组的总和
我的数据看起来像:
read_date | T1 | T2 | 15.02.2000 | 2 | 3 | 16.02.2000 | 4 | 5 | 15.03.2000 | 2 | 3 | 16.03.2000 | 5 | 4 |
我想获得T1和T2的总和,如下所示:
read_date | T1 | T2 | 02.2000 | 6 | 8 | 03.2000 | 7 | 7 |
我试着写这样的东西:
var result = from s in meter_readings.Take(10) group s by new { s.read_date} into g select new { read_date = g.Key.read_date, T1 = g.Sum(x => x.T1), T2 = g.Sum(x => x.T2) };
但这并没有给出预期的数据。是否有任何例子可以提供每小时数据,每日总和等数据。
谢谢
在分组时,您应该只考虑年份和月份:
var result = from s in meter_readings.Take(10) group s by new { date = new DateTime(s.read_date.Year, s.read_date.Month, 1) } into g select new { read_date = g.Key.date, T1 = g.Sum(x => x.T1), T2 = g.Sum(x => x.T2) };
首先,我认为你可以跳过匿名类型:
var result = from s in meter_readings.Take(10) group s by s.read_date into g select new { read_date = g.Key, T1 = g.Sum(x => x.T1), T2 = g.Sum(x => x.T2) };
其次,要按月分组,请使用一些唯一标识月份的值,如下所示:
var result = from s in meter_readings.Take(10) group s by s.read_date.ToString("yyyy.MM") into g select new { read_month = g.Key, T1 = g.Sum(x => x.T1), T2 = g.Sum(x => x.T2) };
您当前的分组将按完整日期分组(即15.02.2000而不是02.2000)。 这将最终为每一天创造一个单独的团体,而不是一个月。
通过(假设它是日期对象)将.Month添加到组中:
group s by new { s.read_date.Month} into g
static void Main() { var list = new List { new meter_reading {Date = new DateTime(2000, 2, 15), T1 = 2, T2 = 3}, new meter_reading {Date = new DateTime(2000, 2, 10), T1 = 4, T2 = 5}, new meter_reading {Date = new DateTime(2000, 3, 15), T1 = 2, T2 = 3}, new meter_reading {Date = new DateTime(2000, 3, 15), T1 = 5, T2 = 4} }; var sum = list .GroupBy(x => GetFirstDayInMonth(x.Date)) .Select(item => new meter_reading { Date = item.Key, T1 = item.Sum(x => x.T1), T2 = item.Sum(x => x.T2), }).ToList(); } private static DateTime GetFirstDayInMonth(DateTime dateTime) { return new DateTime(dateTime.Date.Year, dateTime.Date.Month, 1); }
query.OrderBy(o => o.OrderDate) .GroupBy(o => DbFunctions.CreateDateTime(o.OrderDate.Year, o.OrderDate.Month, 1, 0, 0, 0)) .Select(group => new DateIncomeDto { Date = group.Key.Value, Income = group.Sum(item => item.PayFee ?? 0) });
它对我有用!
上述就是C#学习教程:Linq按日期获得数据组的总和分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1016754.html