gpt4 book ai didi

c# - 如何在 C# 中执行多级聚合?

转载 作者:太空宇宙 更新时间:2023-11-03 22:28:41 25 4
gpt4 key购买 nike

我有以下收藏

PaymentStatus   Amount  Receipt
------------- ------ ---------
Status1 450 123
Status1 54 777
Status2 1230 234
Status2 67 12
Status3 3452 235
Status3 11111 678
Status4 678 156
Status5 346 12
Status5 1000 7
Status6 2000 753

我需要以这样的方式执行分组,以便结果集如下

CollectionUnit  MoneyCollected  NoOfReceipt
--------------- -------------- -------------
Unit1 504 2
Unit2 15860 4
Unit3 678 1
Unit4 3346 3

CollectionUnit的定义

Unit1 who falls in the Status1
Unit2 who falls in the Status2 and Status3
Unit3 who falls in the Status4
Unit4 who falls in the Status5 and Status6

MoneyCollected = Sum(Amount)

NoOfReceipt = 计数(收据)

我已经能够执行第一级聚合

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{

var paymentCollections = new List<Payment>() {
new Payment { PaymentStatus= "Status1", Amount=450, Receipt=123 },
new Payment { PaymentStatus= "Status1", Amount=54, Receipt=777 },
new Payment { PaymentStatus= "Status2", Amount=1230, Receipt=234 },
new Payment { PaymentStatus= "Status2", Amount=67, Receipt=12 },
new Payment { PaymentStatus= "Status3", Amount=3452, Receipt=235 },
new Payment { PaymentStatus= "Status3", Amount=11111, Receipt=678 },
new Payment { PaymentStatus= "Status4", Amount=678, Receipt=156 },
new Payment { PaymentStatus= "Status5", Amount=346, Receipt=12 },
new Payment { PaymentStatus= "Status5", Amount=1000, Receipt=7 },
new Payment { PaymentStatus= "Status6", Amount=2000, Receipt=753 }
};

//level 1 aggregation
var result = paymentCollections.GroupBy(l => l.PaymentStatus)
.Select(cl => new MoneyMovement
{
CollectionUnit = cl.First().PaymentStatus,
MoneyCollected = cl.Sum(c => c.Amount).ToString(),
NoOfReceipt = cl.Count().ToString(),
}).ToList();
Console.ReadKey();
}
}

public class Payment
{
public string PaymentStatus { get; set; }
public float Amount { get; set; }
public int Receipt { get; set; }
}

public class MoneyMovement
{
public string CollectionUnit { get; set; }

public string MoneyCollected { get; set; }

public string NoOfReceipt { get; set; }
}
}

最佳答案

您可以按条件分组。即:

//level 1 aggregation
var result = paymentCollections
.GroupBy(l => new
{
Unit = l.PaymentStatus == "Status1"
? "Unit1"
: l.PaymentStatus == "Status2" || l.PaymentStatus == "Status3"
? "Unit2"
: l.PaymentStatus == "Status4"
? "Unit3"
: l.PaymentStatus == "Status5" || l.PaymentStatus == "Status6"
? "Unit4"
: "Unknown"
})
.Select(cl => new MoneyMovement
{
CollectionUnit = cl.Key.Unit,
MoneyCollected = cl.Sum(c => c.Amount).ToString(),
NoOfReceipt = cl.Count().ToString(),
}).ToList();

关于c# - 如何在 C# 中执行多级聚合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59303710/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com