'Linq Except considering only one property

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?



Solution 1:[1]

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.)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Astrid E.