Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq Except considering only one property

Tags:

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?

like image 376
mo alaz Avatar asked Feb 20 '14 21:02

mo alaz


People also ask

How to use Except in LINQ c#?

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.

What is distinct () in C#?

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

Where and Except LINQ c#?

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.


1 Answers

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();
like image 73
JaredPar Avatar answered Oct 16 '22 23:10

JaredPar