Last active
October 11, 2015 23:28
Quick class for determining changes (additions, removals) in 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 ListDiff | |
{ | |
public static List<ListDiffItem<T>> GetDiff<T>(List<T> oldList, List<T> newList, Func<T, T, bool> equalsFunction = null) | |
{ | |
var combined = new List<ListDiffItem<T>>(); | |
foreach(var i in newList) | |
{ | |
var diff = new ListDiffItem<T>(); | |
diff.Item = i; | |
var existing = equalsFunction != null ? oldList.Any(p => equalsFunction(p, i)) : oldList.Contains(i); | |
diff.Status = existing ? "existing" : "added"; | |
combined.Add(diff); | |
} | |
foreach (var i in oldList) | |
{ | |
var existing = equalsFunction != null ? newList.Any(p => equalsFunction(p, i)) : newList.Contains(i); | |
if (!existing) | |
{ | |
var diff = new ListDiffItem<T>(); | |
diff.Item = i; | |
diff.Status = "removed"; | |
var originalPosition = oldList.IndexOf(i); | |
var newPosition = combined.Count < originalPosition ? combined.Count : originalPosition; | |
combined.Insert(newPosition, diff); | |
} | |
} | |
return combined; | |
} | |
} |
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 class ListDiffItem<T> | |
{ | |
public T Item { get; set; } | |
public string Status { get; set; } | |
} |
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
var combined = ListDiff.GetDiff(oldProcedures, newProcedures, (p1, p2) => p1.ProcedureID == p2.ProcedureID) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment