【问题标题】:C# LINQ: Projecting a detail object into a summary objectC# LINQ:将详细信息对象投影到摘要对象中
【发布时间】:2016-09-26 21:51:43
【问题描述】:

我有一个 .csv,数据如下所示:

Account,Debit,Credit

1,10.00,5.00

1,10.00,10.00

2,5.00,5.00

2,10.00,10.00

此数据填充IEnumerable<Source>。定义如下:

public class Detail {

  public string Account {get; set;}
  public decimal Debit {get; set;}
  public decimal Credit {get; set;}

}

我正在尝试将这个“详细信息”对象合并并投影到一个汇总对象中,其中 Total 是每个帐户的借方和贷方的总和。

public class Summary {

  public string Account {get; set;}
  public decimal Total {get; set;}

}

我要争取的最终结果是一个不同的账户列表,每个账户的所有借方和贷方都汇总起来,这样我就有了一个汇总预测,而不是每个账户/借方/贷方多行。

Account,Debit,Credit


1,5.00,0.00 

2, 0.00, 0.00

假设detailrecordsIEnumerable<Detail> 类型的填充集合。

var results = detailrecords
      .GroupBy(x => x.Account)
      .Select(c => new Summary() {
          Account = ?? I can't figure out how to access my detail properties here 
          Total = ?? I am not sure how to perform arithmetic without access to detail properties
      }).ToList();  

【问题讨论】:

    标签: c# linq


    【解决方案1】:

    你正在寻找的是这样的:

    var results = detailRecords
            .GroupBy(x => x.Account)
            .Select(c => new Summary
            {
                Account = c.Key,
                Total = c.Sum(y => y.Credit + y.Debit)
            }).ToList();
    

    【讨论】:

    • @MikeM 太棒了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-19
    相关资源
    最近更新 更多