getting all email address that does not exists in another list

Anjali Agarwal 1,386 Reputation points
2023-05-03T22:42:45.46+00:00

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))
                        .ToList();

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.

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,208 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,288 questions
C#
C#
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.
10,309 questions
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 56,931 Reputation points
    2023-05-04T16:07:18.4466667+00:00

    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))
        .ToList();
    
    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. SurferOnWww 1,916 Reputation points
    2023-05-04T01:26:04.48+00:00

    Please try the following:

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