Created
April 13, 2018 04:07
-
-
Save frankradocaj/505df1d68205a3d4e1ba39f7c6a51c40 to your computer and use it in GitHub Desktop.
A helper to resolve the list of differences (delta) between two lists
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class DeltaHelper | |
{ | |
public static (IEnumerable<TItem> Left, IEnumerable<TItem> Both, IEnumerable<TItem> Right) Compute<TItem, TValue>( | |
IEnumerable<TItem> list1, | |
IEnumerable<TItem> list2, | |
Func<TItem, TValue> getItemValue) | |
where TValue : IEquatable<TValue> | |
{ | |
var comparableList1 = list1.Select(x => new EqualityComparer<TItem, TValue> | |
{ | |
GetItemValue = getItemValue, | |
Item = x | |
}); | |
var comparableList2 = list2.Select(x => new EqualityComparer<TItem, TValue> | |
{ | |
GetItemValue = getItemValue, | |
Item = x | |
}); | |
return ( | |
Left: comparableList1.Intersect(comparableList2).Select(x => x.Item), | |
Both: comparableList1.Except(comparableList2).Select(x => x.Item), | |
Right: comparableList2.Except(comparableList1).Select(x => x.Item) | |
); | |
} | |
public static (IEnumerable<TItem> Left, IEnumerable<TItem> Both, IEnumerable<TItem> Right) Delta<TItem, TValue>( | |
this IEnumerable<TItem> list1, | |
IEnumerable<TItem> list2, | |
Func<TItem, TValue> getItemValue) | |
where TValue : IEquatable<TValue> | |
{ | |
return Compute(list1, list2, getItemValue); | |
} | |
class EqualityComparer<TItem, TValue> : IEqualityComparer<TItem> | |
{ | |
public Func<TItem, TValue> GetItemValue { get; set; } | |
public TItem Item { get; set; } | |
public bool Equals(TItem x, TItem y) | |
{ | |
return GetItemValue(x).Equals(GetItemValue(y)); | |
} | |
public int GetHashCode(TItem obj) | |
{ | |
return GetItemValue(obj).GetHashCode(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment