I would start with
var res = seq1.Union(seq2, Comparer);
but the documentation for Enumerable.Union
doesn't specify from which sequence a matching element is taken, and requires Comparer
to be an implementation of IEqualityComparer<TSource>
which you won't have if TSource
is an anonymous type (but might be worth making concrete to allow this).
Otherwise you would need to implement you own helper, something like:
IEnumerable<KeyValuePair<TKey, TValue>> Union(
this IEnumerable<KeyValuePair<TKey, TValue>> first,
IEnumerable<KeyValuePair<TKey, TValue>> second) {
var allFirst = first.ToDictionary(v => v.Key, v => v.Value);
foreach (var kv in allFirst) { yield return kv; }
foreach (var s in second) {
if (!allFirst.ContainsKey(s.Key)) {
yield return s;
}
}
(If you want to stick with your own type (properties x & y), you can make this generic over a single type parameter, but you will need to add a type constraint to give access to the separate properties.)