给定以下类和列表:
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);
结果