Reputation: 4769
I have two lists of object.
List<object1> obj1 = new List<object1>();
List<object2> obj2 = new List<object2>();
I want to do this:
obj2 = obj2.Except(obj1).ToList();
However, by reading other questions similar to mine, I understand that this doesn't work unless I override Equals.
I do not want to do that, but both obj2 and obj1 have a string property that is sufficient to see whether they are equal. If obj2.StringProperty
is equivalent to obj1.StringProperty
then the two can be considered equal.
Is there any way I can use Except, but by using only the string property to compare?
Upvotes: 31
Views: 30938
Reputation: 2872
In .Net 6 you can use .ExceptBy()
from System.Linq
.
If your classes contain the following properties:
public class Object1
{
public string String { get; set; }
}
public class Object2
{
public string String { get; set; }
}
.ExceptBy()
can be used like this to compare the two string properties:
var objects1 = new List<Object1>();
var objects2 = new List<Object2>();
// Populate lists
objects2 = objects2
.ExceptBy(
objects1.Select(obj1 => obj1.String)
obj2 => obj2.String) // selecting the String property of Object2 for comparison
.ToList();
Example fiddle here.
(Using .ExceptBy()
has also been suggested by @mjwills in their comment, via MoreLinq.)
Upvotes: 19
Reputation: 755457
The Except
method requires that the two collection types involved have the same element type. In this case the element types are different (object1
and object2
) hence Except
isn't really an option. A better method to use here is Where
obj2 = obj2
.Where(x => !obj1.Any(y => y.StringProperty == x.StringProperty))
.ToList();
Upvotes: 65