2015-02-10 81 views
1

我有2個不同類型的列表,我想按日期分組,然後合併每個日期的2個列表。合併2個不同類型的列表爲1

我的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}, 
} 

謝謝!

+1

你有試過什麼嗎? – Andrei 2015-02-10 11:48:24

回答

1

這裏是第一選擇所有不同日期的方法:

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 wi時間部分。

+0

工作。謝謝! :) – Verendus 2015-02-10 12:24:25

0

你既可以創建一個第三類

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

或最終使用的元組列出

List<Tuple<Date, Invoice, Payment>>(); 
相關問題