Skip to content

Instantly share code, notes, and snippets.

@DominicFinn
Created March 2, 2012 17:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save DominicFinn/1959717 to your computer and use it in GitHub Desktop.
Save DominicFinn/1959717 to your computer and use it in GitHub Desktop.
Two ways of generating the difference in between two lists
using System.Collections.Generic;
using System.Linq;
namespace Other.Something.Core.Tasks
{
public static class DiffGenerator
{
public static Diff<T> Generate<T>(IEnumerable<T> left, IEnumerable<T> right)
{
var added = right.Except(left);
var removed = left.Except(right);
var leftList = left;
var common = right.Where(leftList.Contains);
return new Diff<T>(added, removed, common);
}
public static IEnumerable<IEnumerable<T>> GenerateClassic<T>(IEnumerable<T> left, IEnumerable<T> right)
{
var oldList = new Queue<T>(left);
var newList = new List<T>(right);
var removed = new List<T>();
var common = new List<T>();
while (oldList.Count > 0)
{
var currentItem = oldList.Dequeue();
if (newList.Contains(currentItem))
{
newList.Remove(currentItem);
common.Add(currentItem);
}
else
{
removed.Add(currentItem);
}
}
return new List<List<T>>()
{
common, newList, removed
};
}
}
public sealed class Diff<T>
{
public IEnumerable<T> Added { get; private set; }
public IEnumerable<T> Removed { get; private set; }
public IEnumerable<T> Common { get; private set; }
internal Diff(IEnumerable<T> added, IEnumerable<T> removed, IEnumerable<T> common)
{
Added = added;
Removed = removed;
Common = common;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment