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?
LINQ: ExceptThe Except() method requires two collections. It returns a new collection with elements from the first collection which do not exist in the second collection (parameter collection). Except extension method doesn't return the correct result for the collection of complex types.
C# Linq Distinct() method removes the duplicate elements from a sequence (list) and returns the distinct elements from a single data source. It comes under the Set operators' category in LINQ query operators, and the method works the same way as the DISTINCT directive in Structured Query Language (SQL).
What is LINQ Except in C#? The LINQ Except Method in C# is used to return the elements which are present in the first data source but not in the second data source. There are two overloaded versions available for the LINQ Except Method as shown below.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With