Problem:
I have two arrays that can possibly be different lengths. I need to iterate through both arrays and find similarities, additions, and deletions.
I wrote this a while back:
Usage:
foreach (var diff in Foo_Old.Diff(Foo_New)){
Console.WriteLine ("{0} action performed on {1}",diff.DiffAction,diff.Value);
}
Implementation:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LinqExtensions {
enum DiffAction {
Added,
Removed,
Same
}
class DiffPair {
public T Value { get; set; }
public DiffAction DiffAction { get; set; }
}
static class DiffExtension {
public static IEnumerable> Diff
(
this IEnumerable original,
IEnumerable target
) {
Dictionary results = new Dictionary();
foreach (var item in original) {
results[item] = DiffAction.Removed;
}
foreach (var item in target) {
if (results.ContainsKey(item)) {
results[item] = DiffAction.Same;
} else {
results[item] = DiffAction.Added;
}
}
return results.Select(
pair => new DiffPair {
Value=pair.Key,
DiffAction = pair.Value
});
}
}
}