Reputation: 13
I have 2 Lists, both are business objects.
First object is
public class Mail
{
string id;
string name;
string address;
....
}
Second object is
public class DoNotMail
{
string id;
string otherinfo;
....
}
The lists are
List<Mail> _mailList
List<DoNotMail> _doNotMailList
I need to a linq query to get all the Mail items where the Mail.Id is not in DoNotMail.id
If this were normal sql, I think I'd do a left join where DoNotMail.id is null, but every attempt I tried to do it in linq isn't working right.
Any ideas?
Upvotes: 1
Views: 106
Reputation: 5999
Try This:
var results = from m in _mailList
where !(from nm in _doNotMailList select nm.Id)
.Contains(m.Id)
select m;
It is equal to not in un Sql.
Upvotes: 1
Reputation: 26644
If you override the Equals method in both classes you can use this:
_mailList.Except(_doNotMailList).ToList();
Upvotes: 1
Reputation: 130
Try
var query = from m in Mail where !(from d in DoNotMail select d.Id) .Contains(m.Id) select m;
Upvotes: 0
Reputation: 15242
var mailItem = _mailList.Where(x => !_doNotMailList.Contains(x.id));
Upvotes: 1
Reputation: 1500525
Simplest approach:
var doNotMailIds = new HashSet<string>(_doNotMailList.Select(x => x.id));
var mailItems = _mailList.Where(x => !doNotMailIds.Contains(x.id));
That's assuming you want want the full Mail
items. If you only need their IDs, you can do it in one query:
var mailIds = _mailList.Select(x => x.id)
.Except(_doNotMailList.Select(x => x.id));
Upvotes: 5