I have two Lists that I'm trying to compare. What I need to accomplish is essentially to remove the items that are duplicated between the two lists and only keep the objects that are different. Right now, I'm inserting the non-duplicate data into a new list.
The data I'm using here...
LIST1 ("b",2) ("c",3)
LIST2 ("a",1) ("b",2) ("c",3) ("d",4)
NEWLIST ("a",1) ("d",4)
Here's what I have so far...
My object:
public class TestClass
{
protected string teststring;
protected int testint;
public string TestString
{
get { return teststring; }
set { teststring = value; }
}
public int TestInt
{
get { return testint; }
set { testint = value; }
}
public TestClass() { }
}
My compare logic:
private static List<TestClass> CompareCodes(List<TestClass> list1, List<TestClass> list2)
{
List<TestClass> newList = new List<TestClass>();
foreach (TestClass s in list2)
{
if (list1.Contains(s) == false)
{
newList.Add(s);
}
}
if (newList.Count != 0)
return newList;
else
return null;
}
The new list will be used to insert data into a database table. If it's null, no action will be taken. I'm using .NET 2.0 in this app (it's an enhancement to an older app), so I can't use LINQ. So is there any other way to make this work that I'm missing? Or is there a better way to do this? I haven't been able to find anything (maybe just not looking hard enough) to accomplish what I'm trying to do.
Thanks in advance!
So you're almost there, but you'll need to override the
Equals
method on your class to make it work:Use Jon Skeet's answer here to implement your hash code.