I have this
var n = ItemList.Select(s => new { s.Vchr, s.Id, s.Ctr, s.Vendor, s.Description, s.Invoice }).ToList();
n.AddRange(OtherList.Select(s => new { s.Vchr, s.Id, s.Ctr, s.Vendor, s.Description, s.Invoice }).ToList(););
I would like to do this if it where allowed
n = n.Distinct((x, y) => x.Vchr == y.Vchr)).ToList();
I tried using the generic LambdaComparer but since im using anonymous types there is no type associate it with.
"Help me Obi Wan Kenobi, you're my only hope"
I note that JaredPar's answer does not quite answer the question since the set methods like Distinct and Except require an
IEqualityComparer<T>
not anIComparer<T>
. The following assumes that an IEquatable will have a suitable GetHashCode, and it certainly has a suitable Equals method.Where the same inference from a static class trick is used as in JaredPar's answer.
To be more general you could provide two
Func
s: aFunc<T, T, bool>
to check equality andFunc<T, T, int>
to select a hash code.The trick is to create a comparer that only works on inferred types. For instance:
Now I can do the following ... hacky solution:
Most of the time when you compare (for equality or sorting) you're interested in choosing the keys to compare by, not the equality or comparison method itself (this is the idea behind Python's list sort API).
There's an example key equality comparer here.