Search code examples
.netlinqentity-framework-6

Find all objects with list attribute element that exist in another list


I have two lists. One is of type AppUser that comes from the database and the other is of type customer that is passed in as a parameter. Here are the class definitions.

public class AppUser
{
  public int Id{get;set;}
  public string Name{get;set;}
  public IEnumerable<Customer> customers{get;set;}
}

public class Customer
{
  public int Id{get;set;}
  public string Name{get;set;}
  public IEnumerable<User> users{get;set;}
}

I am attempting to create an API endpoint that will allow a person to pass in a list of Customers and get back all the unique users in the database for that list of customers. So what I have is a list attribute for the users that needs to be compared to a list of customers being passed in to the API. I the following code but it does not work. I am somewhat new to linq so am really confused.

var joinUsers = repoUsers.Join(
   customers, 
   uObj => uObj, 
   cObj => cObj, 
   (uObj, cObj) => uObj
);

repoUsers is my list of users from the database with each having a customers list as an attribute.

customers is my list of customers passed into my API.

How can I join my repoUsers object using it's customers list attribute compared to the customers list passed in and return the repoUsers that match a customer in the customers list?


Solution

  • Project your input to an IEnumerable of IDs then use the Contains method on the Customer.Id. Finish up by using SelectMany to aggregate each customer’s Users property then Distinct to remove duplicates

    var cutomerIDs = customers.Select( c => c.Id );
    
    var usersQuery = dbContext.Customers
        .Where( c => customerIDs.Contains( c.Id ) )
        .SelectMany( c => c.Users )
        .Distinct();