LINQ to Objects List Difference

后端 未结 5 1054
有刺的猬
有刺的猬 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 ret = new List( );
    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
    }
    

提交回复
热议问题