Saturday, August 29, 2015

C# Test for Except And Intersect

I needed to compare two Lists in C# in order to form a new List by comparing the Lists, adding the common elements to the new List, and then adding new elements to the new List. I thought it good to share and perhaps garner some feedback. Here is the NUnit test:
[Test]
public void TestExceptAndIntersect()
{
//check if equal with differing sequence
var list1 = new List<int>(new int[] { 1, 2, 3, 4, 5, 6 });
var list2 = new List<int>(new int[] { 6, 5, 4, 3, 2, 1 });
var result = list1.Except(list2).ToList();
Assert.AreEqual(new int[] { }, result);
var oldList = new List<int>(new int[] { 1, 2, 3, 4, 5, 6 });
var newList = new List<int>(new int[] { 3, 5, 6, 7, 8 });
//get the intersect between the 2 lists
var commonItems = newList.Intersect(oldList).ToList();
Assert.AreEqual(new int[] { 3, 5, 6 }, commonItems);
//what is in the first list that is not in the second list
var toBeRemoved = oldList.Except(newList).ToList();
var toBeAdded = newList.Except(oldList).ToList();
Assert.IsFalse(toBeRemoved.Count == 0);
Assert.IsFalse(toBeAdded.Count == 0);
Assert.AreEqual(new int[] { 1, 2, 4 }, toBeRemoved);
Assert.AreEqual(new int[] { 7, 8 }, toBeAdded);
var updatedList = commonItems.Concat(toBeAdded).ToList();
Assert.AreEqual(new int[] { 3, 5, 6, 7, 8 }, updatedList);
}
view raw gistfile1.txt hosted with ❤ by GitHub