-4

我有两个清单List<Collection> collectionsList<Invoice>发票。两者都有一个 CurrencyID 字段和一个 Value 字段。我需要的是按 currencyID 对这两个列表进行分组,并将收集到的值减去发票值。而且这仅在匹配的情况下,否则,无论在哪个列表中都会出现不匹配,我将在最终列表中需要它。例如:

invoices        collections         final
30 EUR              10 USD          10 EUR
40 CAN              20 EUR          40 USD     
50 USD              50 JPN          40 CAN
                                    50 JPN
4

1 回答 1

2

给定以下类和列表:

class Collection { public string CurrencyID; public Int32 Value; }
class Invoice { public string CurrencyID; public Int32 Value; }

...

List<Collection> collections = new List<Collection> {
    new Collection() {CurrencyID="USD", Value=10},
    new Collection() {CurrencyID="EUR", Value=20},
    new Collection() {CurrencyID="JPN", Value=50}
};

List<Invoice> invoices = new List<Invoice> {
    new Invoice() {CurrencyID="USD", Value=50},
    new Invoice() {CurrencyID="EUR", Value=30},
    new Invoice() {CurrencyID="CAN", Value=40}
};

你可以通过两个简单的查询得到你想要的,然后使用Union.

var result1 = (from i in invoices
               let o = collections.SingleOrDefault(x => x.CurrencyID == i.CurrencyID)
               select new 
               {
                  CurrencyID = i.CurrencyID,
                  Value = i.Value - (o != null ? o.Value : 0)
               }).ToList();

var result2 =  from c in collections
               where !result1.Any(x => x.CurrencyID == c.CurrencyID)
               select new 
               {
                CurrencyID = c.CurrencyID,
                Value = c.Value
               };

var result = result1.Union(result2).OrderBy (r => r.Value);

结果

在此处输入图像描述

于 2012-09-04T13:29:07.790 回答