linq加入两个动态大小的列表

时间:2012-09-04 12:47:54

标签: c# .net linq

我有两个列表,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

1 个答案:

答案 0 :(得分: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); 组合它们。

{{1}}

<强>结果

enter image description here