3

我有一个名为发票列表的列表,其中包含以下项目。

ID:1
Total:5
Description:Test
Date:2012-01-01
Difference:

ID:2
Total:10
Description:Test
Date:2012-02-01
Difference:

ID:3
Total:15
Description:Test
Date:2012-03-01
Difference: 

ID:4
Total:20
Description:Test
Date:2012-04-01
Difference:

我需要使用 LINQ 计算每个发票 ID 之间的差异(最好)。最终输出应如下所示:

 ID:1
    Total:5
    Description:Test
    Date:2012-01-01
    Difference:0

    ID:2
    Total:10
    Description:Test
    Date:2012-02-01
    Difference:5

    ID:3
    Total:15
    Description:Test
    Date:2012-03-01
    Difference: 5

    ID:4
    Total:20
    Description:Test
    Date:2012-04-01
    Difference:5

有人可以建议实现上述目标的最佳方法吗?

4

2 回答 2

8

我怀疑Zip是你的朋友在这里:

var withNull = new Invoice[] { null }.Concat(invoices);

var withDifference = withNull.Zip(withNull.Skip(1),
                                  (x, y) => x == null ? y :
                                      new Invoice { 
                                          ID = y.ID,
                                          Total = y.Total,
                                          Date = y.Date,
                                          Difference = y.Total - x.Total
                                      }
                                  )
                             .ToList();

我将把它的工作原理(以及为什么你需要 null)作为练习——如果有必要,我可以给出一些提示......

于 2012-08-13T07:40:46.110 回答
2

由于源是一个列表,您可以使用索引来引用前一个项目,这可以使用 select 的替代形式来实现,该形式使用基于项目及其索引的 func。

var results=invoices.Select((x,i) => new Invoice { 
        Total = x.Total,
        Date = x.Date,
        Description=x.Description,
        Difference = x.Total - (i==0 ? 0 : invoices[i-1].Total)}
        );

.ToList()如果您希望结果作为列表,您可以在最后使用

于 2012-08-13T07:50:41.927 回答