如何使用正确的总计和分组创建对象

时间:2017-02-10 20:00:58

标签: c#

我尝试创建一个需要按BatchCode分组并在某些字段上合计的对象。我尝试使用Groupby功能完成此操作,但我遇到了困难,任何帮助都会受到赞赏。

输入记录:
记录1:

BatchCode 1234  
BatchType Scanned  
Amount    10.00  
RecType   Adc

记录2:

BatchCode 1234  
BatchType Scanned  
Amount    5.00  
RecType   NotAdc

记录3:

BatchCode 2222
BatchType NonScanned  
Amount    25.00  
RecType   Adc

记录4:

BatchCode 2222
BatchType NonScanned  
Amount    30.01  
RecType   NotAdc

预期输出对象:

    "Batches": [
    {
      "BatchCode": "1234",
      "BatchType": "Scanned",
      "DetailRecordCountAdc": 1,
      "DetailRecordCountNotAdc": 1,
      "DetailRecordCountTotal": 2,
      "AmountAdc": 10.00,
      "AmountNotAdc": 5.00,
      "AmountTotal": 15.00
    },
    {
      "BatchCode": "2222",
      "BatchType": "Nonscanned",
      "DetailRecordCountAdc": 1,
      "DetailRecordCountNotAdc": 1,
      "DetailRecordCountTotal": 2,
      "AmountAdc": 25.00,
      "AmountNotAdc": 30.01,
      "AmountTotal": 55.01
    }
  ]        

1 个答案:

答案 0 :(得分:1)

为了实现这一目标,我继续做了一些假设。我主要假设您的实体是如何设置的。

以下是我如何设置它们:

public enum BatchType
{
    Scanned = 1,
    NonScanned = 2
}

public enum RecType
{
    Adc = 1,
    NotAdc = 2
}

public class Batch
{
    public int BatchCode { get; set; }
    public BatchType BatchType { get; set; }
    public double Amount { get; set; }
    public RecType RecType { get; set; }
}

public class BatchGroup
{
    public int BatchCode { get; set; }
    public BatchType BatchType { get; set; }
    public int DetailRecordCountAdc { get; set; }
    public int DetailRecordCountNotAdc { get; set; }
    public int DetailRecordCountTotal => DetailRecordCountAdc + DetailRecordCountNotAdc;
    public double AmountAdc { get; set; }
    public double AmountNotAdc { get; set; }
    public double AmountTotal => AmountAdc + AmountNotAdc;
}

一旦我有了这样的类,我就用正确的值创建了每个对象:

var list = new[]
{
    new Batch
    {
        BatchCode = 1234,
        BatchType = BatchType.Scanned,
        Amount = 10.00,
        RecType = RecType.Adc
    },
    new Batch
    {
        BatchCode = 1234,
        BatchType = BatchType.Scanned,
        Amount = 5.00,
        RecType = RecType.NotAdc,
    },
    new Batch
    {
        BatchCode = 2222,
        BatchType = BatchType.NonScanned,
        Amount = 25.00,
        RecType = RecType.Adc,
    },
    new Batch
    {
        BatchCode = 2222,
        BatchType = BatchType.NonScanned,
        Amount = 30.01,
        RecType = RecType.NotAdc,
    }
};

随着一切就绪,我做了LINQ声明。

var result = list.GroupBy(x => new { x.BatchCode, x.BatchType }).Select(x => new BatchGroup
{
    BatchCode = x.Key.BatchCode,
    BatchType = x.Key.BatchType,
    DetailRecordCountAdc = x.Count(y => y.RecType == RecType.Adc),
    DetailRecordCountNotAdc = x.Count(y => y.RecType == RecType.NotAdc),
    AmountAdc = x.Where(y => y.RecType == RecType.Adc).Sum(y => y.Amount),
    AmountNotAdc = x.Where(y => y.RecType == RecType.NotAdc).Sum(y => y.Amount)
});