getting all email address that does not exists in another list

Anjali Agarwal 941 Reputation points

I have two List of objects like this:

List<EmployeeInfo> emp = getEmployees();
List<EmailList> emailist = getMasterList();

I want to get all the employees email address, firstname, lastName that exists in emailList, but do not exists in emp list. In other words, I want to exclude the email address of the users that exists in emp list. I wrote below LINQ to achieve this:

  List<EmployeeInfo> result = emp
                     .Where(w => !emailist.Contains(w.EmailAddress))

above keeps giving me an error saying "cannot convert from string to emailList.

This is the model for both employeeInfo and emailList

public partial class EmployeeInfo
    public int EmployeeInfoId { get; set; }
    public DateTime DateFormFilled { get; set; }
    public string EmployeeNumber { get; set; } = null!;
    public string LastName { get; set; } = null!;
    public string FirstName { get; set; } = null!;
    public string? MiddleName { get; set; }
    public string EmailAddress { get; set; } = null!;
public partial class EmailList {
public string? LastName { get; set; }
public string? FirstName { get; set; }
public string? Eid { get; set; }
public string? Email { get; set; }
public DateTime LoadDate { get; set; }

any help will be appreciated.

A set of technologies in the .NET Framework for building web applications and XML web services.
3,168 questions
A Microsoft web application framework that implements the model-view-controller (MVC) design pattern.
856 questions
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
8,237 questions
{count} votes

Accepted answer
  1. Bruce ( 36,431 Reputation points

    as suggested you use the Any() instead of Contains(). Now this will be a nested loop and pretty slow if the lists are large - O(n^2). convert the knockout list to a hash set and its linear O(1):

    var emailHash = new HashSet<string>(emailList.Select(r => r.EmailAddress));
    List<Employee> result = emp
        .Where(r => !emailHash.Contains(r.EmailAddress))
    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. SurferOnWww 1,036 Reputation points

    Please try the following:

    List<Employee> result = emp
        .Where(w => emailist.FirstOrDefault(m => m.Email == w.EmailAddress) == null)