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
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
}
list1.Except(list2);
EDIT: Example here.
List<String> list1 = new List<string>();
List<String> list2 = new List<string>();
List<String> list3 = list1.Except(list2).ToList();
You can use the Except linq method:
var list1 = // First list generation
var list2 = // Second list generation
var result = list1.Except(list2);
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;