Skip to content

Instantly share code, notes, and snippets.

@lukencode
Last active October 11, 2015 23:28
Show Gist options
  • Save lukencode/3936522 to your computer and use it in GitHub Desktop.
Save lukencode/3936522 to your computer and use it in GitHub Desktop.
Quick class for determining changes (additions, removals) in lists
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;
}
}
public class ListDiffItem<T>
{
public T Item { get; set; }
public string Status { get; set; }
}
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