Created
August 19, 2016 11:27
-
-
Save battermann/26f83854aeb95cf8fd4ae63cdf19c4cd to your computer and use it in GitHub Desktop.
This file contains 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 class EditedPair<T> | |
{ | |
public EditedPair(T old, T @new) | |
{ | |
Old = old; | |
New = @new; | |
} | |
public T Old { get; private set; } | |
public T New { get; private set; } | |
} | |
public class CollectionDif<T> | |
{ | |
public CollectionDif(IEnumerable<T> added, IEnumerable<T> deleted, IEnumerable<EditedPair<T>> edited) | |
{ | |
Added = added; | |
Deleted = deleted; | |
Edited = edited; | |
} | |
public IEnumerable<T> Added { get; private set; } | |
public IEnumerable<T> Deleted { get; private set; } | |
public IEnumerable<EditedPair<T>> Edited { get; private set; } | |
} | |
public static class Extensions | |
{ | |
public static IEnumerable<T> FindAdded<T, TKey>(this IEnumerable<T> newList, IEnumerable<T> oldList, Func<T, TKey> keySelector) | |
{ | |
return newList.Where(n => !oldList.Any(o => keySelector(n).Equals(keySelector(o)))); | |
} | |
public static IEnumerable<T> FindDeleted<T,TKey>(this IEnumerable<T> newList, IEnumerable<T> oldList, Func<T, TKey> keySelector) | |
{ | |
return oldList.FindAdded(newList, keySelector); | |
} | |
public static IEnumerable<EditedPair<T>> FindEdited<T, TKey, TValue>(this IEnumerable<T> newList, IEnumerable<T> oldList, Func<T, TKey> keySelector, Func<T, TValue> valueSelector) | |
{ | |
var commonElements = newList.Where(n => oldList.Any(o => keySelector(n).Equals(keySelector(o)))); | |
return commonElements | |
.Select(e => new { New = e, Old = oldList.Single(x => keySelector(e).Equals(keySelector(x))) }) | |
.Where(t => !valueSelector(t.Old).Equals(valueSelector(t.New))) | |
.Select(t => new EditedPair<T>(old: t.Old, @new: t.New)); | |
} | |
public static CollectionDif<T> FindDiff<T, TKey, TValue>(this IEnumerable<T> newList, IEnumerable<T> oldList, Func<T, TKey> keySelector, Func<T, TValue> valueSelector) | |
{ | |
return new CollectionDif<T>( | |
added: newList.FindAdded(oldList, keySelector), | |
deleted: newList.FindDeleted(oldList, keySelector), | |
edited: newList.FindEdited(oldList, keySelector, valueSelector)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment