Search code examples
c#asp.netlinq

How to handle multiple optional filters in a C# LINQ query?


I'm trying to create a GET method with different optional filters, I want that if any of the filters is null, it doesn't filter for that field. I have the following code but if it enters more than one where it does not work. How can I solve my problem?

 public List<GetUserResponseDto> GetUsers(GetUserParametersDto parameters)
        {
            UserRepository userRepository = new(_context);
            IQueryable<User> query = userRepository.GetAll();

            if (parameters.Status?.Count > 0)
            {
                query = query.Where(p => parameters.Status.Contains(p.State)); 
            }

            if (!string.IsNullOrEmpty(parameters.Platform))
            {
                query = query.Where(p => string.Equals(p.Platform, parameters.Platform, StringComparison.OrdinalIgnoreCase));
            }

            if (!string.IsNullOrEmpty(parameters.IdentityCardNumber))
            {
                query = query.Where(p => string.Equals(p.IdentityCardNumber, parameters.IdentityCardNumber, StringComparison.OrdinalIgnoreCase));
            }

            return query.Select(GetUserResponseDtoMapper.FromUser).ToList(); 
        }

I have tried to do it with different wheres but it has not worked, I have also tried to create a dynamic predicate but I have not succeeded.


Solution

  • You could use && and || to combine the filters. Use or to make them optional for example:

    string filter1
    string filter2
    
    result = dataSource.Where(e =>
        (filter1 is null || e.Contains(filter1)) &&
        (filter2 is null || e.Contains(filter2))
        ).ToList();
    

    Would that work for you?