次のクラスとリストがあるとします。
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}
};
2つの簡単なクエリを実行して必要なものを取得し、を使用してそれらを組み合わせることができます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);
結果