LINQ to Objects List Difference

后端 未结 5 1002
有刺的猬
有刺的猬 2021-01-20 20:55

I have two EmailAddress generic lists, I wanted a simple way of just getting all the EmailAddress objects that are in List1 that aren\'t in List2.

I\'m thinking a le

相关标签:
5条回答
  • 2021-01-20 21:17

    Well, I am sure that people will come in here and give you a more hip, LINQesque example, but my employer only 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 overriding 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
    }
    
    0 讨论(0)
  • 2021-01-20 21:17

    list1.Except(list2);

    EDIT: Example here.

    0 讨论(0)
  • 2021-01-20 21:22
            List<String> list1 = new List<string>();
            List<String> list2 = new List<string>();
            List<String> list3 = list1.Except(list2).ToList();
    
    0 讨论(0)
  • 2021-01-20 21:30

    You can use the Except linq method:

    var list1 = // First list generation
    var list2 = // Second list generation
    
    var result = list1.Except(list2);
    
    0 讨论(0)
  • 2021-01-20 21:34

    Most of these answers will not work since the items in List1 and List2 may be equal in the eyes of the user, but are actually references to different instances (they are not reference equal).

    Assuming Address is a string property of EmailAddress, here's a left join solution.

    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;
    
    0 讨论(0)
提交回复
热议问题