LINQ to the difference in the list of objects

I have two common EmailAddress lists, I need an easy way to just get all the EmailAddress objects that are in List1 that are not in List2.

I am thinking about externally connecting with Linq, but I'm a little confused about how to do this. I am also open to a better solution.

Update: I should have noted that these are lists of user data types of my "EmailAddress" objects.

+3
source share
5 answers

Most of these answers will not work, because the elements in List1 and List2 may be equal in the eyes of the user, but in fact are links to different instances (they are not reference).

- EmailAddress, .

IEnumerable<EmailAddress> query = 
  from a1 in list1
  join a2 in list2 on a1.Address equals a2.Address into g
  from x in g.DefaultIfEmpty()
  where x == null
  select a1;
+2

Except linq:

var list1 = // First list generation
var list2 = // Second list generation

var result = list1.Except(list2);
+9

Well, I'm sure people will come here and give you an example with hips, LINQesque, but my employer allows us to use .NET 2.0, so ...

List<EmailAddress> ret = new List<EmailAddress>( );
foreach ( EmailAddress address in List1 )
{
    if( !List2.Contains( address ) )
    {
        ret.Add( address );
    }
}

Here is an example of an override of the .Equals method that may apply to you.

class EmailAddress
{
    public string Address { get; set; }

    public override bool Equals( object o )
    {
        EmailAddress toCheck = o as EmailAddress;
        if( toCheck == null ) return false;
        // obviously this is a bit contrived, but you get the idea
        return ( this.Address == toCheck.Address );
    }

    // override GetHashCode as well when overriding Equals
}
+1
source

list1.Except(list2);

EDIT: An example is here .

0
source
        List<String> list1 = new List<string>();
        List<String> list2 = new List<string>();
        List<String> list3 = list1.Except(list2).ToList();
0
source

Source: https://habr.com/ru/post/1751459/


All Articles