If I have two generic lists. How do I find what’s NOT in the other list using LINQ?
Here is my obj class:
public class tobj
{
public string column1;
public string column2;
}
Here are the arrays
tobj[] array1 =
{
new tobj { "1", "1" }, new tobj { "2", "2" }, new tobj { "3", "3" }
};
tobj[] array2 =
{
new tobj { "2", "2" }, new tobj { "3", "3" }, new tobj { "4", "4" }
};
var diff = array1.FinfDiff(array2);
foreach (var value in diff)
{
Console.WriteLine(value.column1); // 1
}
This code not tested yet.
You can use
Except. Given that you have a custom type, though, you’ll want to overrideEquals()andGetHashCode()so that it works well with Linq.This is because Linq strives for efficiency, so it can use
HashSet<T>and other mechanisms to quickly determine if items are possibly equivalent or not (items that are equivalent must have same hash code, or your hash code is bad). So it’s not just enough to implementEquals(), you must also implementGetHashCode()when using methods of this type with custom classes.For example:
Now that you have GetHashCode() and Equals() overridden (I like implementing
IEquatable<T>myself as well), you can useExcept():I’d recommend seeing this SO thread on algorithms for hash codes as well for tips on implementing a good one.
Also, as a side note, some types (such as
KeyValuePair,Tuple, and anonymous types) already implementEquals()andGetHashCode()correctly for equivalence in such a way that they take into account their individual components.