linq 如何获取每条记录值与前一条记录值差异

edqdpe6u  于 2022-12-06  发布在  其他
关注(0)|答案(1)|浏览(186)

请考虑下表:

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创建这个结果。谢谢

3pmvbmvn

3pmvbmvn1#

您需要将数据源与其自身联接,以获取所有成对的(monthStart,monthEnd)记录,然后计算差值:

from monthStart in dataSource
join monthEnd in dataSource
on new { monthStart.Code, date = monthStart.Year * 12 + monthStart.Month }
equals new { monthEnd.Code, date = monthEnd.Year * 12 + monthEnd.Month - 1}
select new {
  monthStart.Code,
  FromYear = monthStart.Year,
  FromMonth = monthStart.Month,
  ToYear = monthEnd.Year,
  ToMonth = monthEnd.Month,
  Difference = monthEnd.Value - monthStart.Value
}

相关问题