如何用LINQ计算每条记录与前一条记录的差值
使用LINQ计算同Code下相邻月份的数值差
原始数据
Year Month Code Value -------------------------------- 2011 1 1 100 2011 2 1 200 2011 3 1 250 2011 1 2 70 2011 2 2 50 2011 3 2 80
期望结果
Code FromYearMonth ToYearMonth Difference ---------------------------------------------------- 1 2011-1 2011-2 100 <----200 - 100 1 2011-2 2011-3 50 <----250 - 200 2 2011-1 2011-2 -20 <----50 - 70 2 2011-2 2011-3 30 <----80 - 50
请问如何使用LINQ实现该结果?
实现方案
首先定义对应原始数据的实体类:
public class DataItem { public int Year { get; set; } public int Month { get; set; } public int Code { get; set; } public int Value { get; set; } }
假设原始数据已存入List<DataItem> dataList集合,用以下LINQ代码实现需求:
var result = dataList // 按Code分组,确保同Code的数据聚合在一起 .GroupBy(item => item.Code) // 遍历每个分组,生成相邻月份的差值记录 .SelectMany(group => // 分组内按年、月排序,保证月份顺序正确 group.OrderBy(item => item.Year).ThenBy(item => item.Month) // 用Zip将当前元素与下一个元素配对 .Zip(group.OrderBy(item => item.Year).ThenBy(item => item.Month).Skip(1), (prevMonth, currMonth) => new { Code = group.Key, FromYearMonth = $"{prevMonth.Year}-{prevMonth.Month}", ToYearMonth = $"{currMonth.Year}-{currMonth.Month}", Difference = currMonth.Value - prevMonth.Value, Calculation = $"{currMonth.Value} - {prevMonth.Value}" }) ) // 按Code和起始年月排序,匹配期望结果的顺序 .OrderBy(item => item.Code).ThenBy(item => item.FromYearMonth) .ToList();
关键步骤说明
- 分组:
GroupBy按Code拆分数据,确保后续只处理同一Code下的月份数据。 - 排序:每个分组内按
Year和Month排序,避免因原始数据乱序导致相邻配对错误。 - 相邻元素配对:
Zip方法将排序后的集合与跳过第一个元素的同集合合并,得到(上月数据, 当月数据)的配对。 - 结果构造:计算当月与上月的数值差,同时格式化年月字符串,若不需要显示计算过程可去掉
Calculation字段。
如果需要输出成示例中的文本表格,可遍历结果集合拼接输出:
Console.WriteLine("Code FromYearMonth ToYearMonth Difference"); Console.WriteLine("----------------------------------------------------"); foreach (var item in result) { Console.WriteLine($"{item.Code,4} {item.FromYearMonth,16} {item.ToYearMonth,16} {item.Difference,8} <----{item.Calculation}"); }
内容的提问来源于stack exchange,提问作者DooDoo
相关产品推荐
相关产品推荐

