将 2 个不同类型的列表合并为 1 个

Merge 2 list of different types into 1

我有 2 个不同类型的列表,我想按日期分组,然后合并每个日期的 2 个列表。

我的 2 列表看起来像这样。

List<Payment> payments = new List<Payment>
{
    new Payment{Date = '2014-01-01 12:23:52', PaymentSum = 300},
    new Payment{Date = '2014-01-01 12:23:53', PaymentSum = 100},
    new Payment{Date = '2014-01-02 12:23:52', PaymentSum = 300},
}

List<Invoice> invoices = new List<Invoice>
{
    new Invoice{Date = '2014-01-01 12:20:32', InvoiceSum= 300},
    new Invoice{Date = '2014-01-01 12:21:53', InvoiceSum= 200},
    new Invoice{Date = '2014-01-02 12:24:52', InvoiceSum= 300},
}

我希望结果看起来像这样:

List<NewItem> newItems= new List<NewItem>
{
    new NewItem{Date = '2014-01-01', InvoiceSum= 500, PaymentSum = 400},
    new NewItem{Date = '2014-01-02', InvoiceSum= 300, PaymentSum = 300},
}

提前致谢!

您可以创建第三种类型

class ThirdType {
    public Invoice Invoice { get; set; }
    public Payment Payment { get; set; }
}

或在结果列表中使用元组

List<Tuple<Date, Invoice, Payment>>();

这是一种首先选择所有不同日期的方法:

var dateSums = payments
    .Select(p => p.Date.Date)
    .Concat(invoices.Select(i => i.Date.Date))
    .Distinct()
    .Select(d => new
    {
        Date = d,
        InvoiceSum = invoices
            .Where(i => i.Date.Date == d)
            .Sum(i => i.InvoiceSum),
        PaymentSum = payments
            .Where(i => i.Date.Date == d)
            .Sum(i => i.PaymentSum)
    });

请注意,我使用的是 Date.Date,因为 属性 是带有时间部分的 DateTime