Search code examples
c#arrays.netlinqsplit

Using LINQ to retrieve multiple records that fit criteria


I have a FE that allows a user to filter based on different criteria. One of these criteria is Business Units. When a user selects this filter the URL looks like this: https://localhost:7206/api/v1/lots?businessUnits=SCP_PP

This works fine and I can filter based on this. However, I now want to add multi filter search functionality so the URL would now look like:

https://localhost:7206/api/v1/lots?businessUnits=SCP_PP%2CNAG

In C#, this comes through as a string "SCP_PP, NAG" and I am unsure how to return records that fit both criteria. The rest of my code is here:

public ActionResult<List<LotDTO>> GetLots(DateTime? dateFrom, DateTime? dateTo, bool? includeGraded, string? status, string? businessUnits) { ...return lots; }

This controller works fine when it is just one criteria. The actual method that implements the search is here:

public List<Lot> GetLots(DateTime? dateFrom, DateTime? dateTo, bool? includeGraded, string? status, string? businessUnits)
    {
        var lots = _gradingContext.Lots.AsNoTracking().AsQueryable();

        if(businessUnits!= null)
        {
            if (businessUnits.Contains(','))
            {
                string[] businessUnitsTemp = businessUnits.Split(",");
                foreach (var unit in businessUnitsTemp)
                {
                    lots = lots.Where(x => x.BusinessUnit.Equals(businessUnitsTemp));
                }
            }
            else
            {
                lots = lots.Where(x => x.BusinessUnit.Equals(businessUnits));
            }
        }

        return lots.ToList();
    }

Since it comes through as a string and I need to seperate however many there are, I thought I would start by checking if there is a comma in the string - if there splitting on the comma, then storing the different values into an array.

I would then iterate through the array, and for each different entry get the lots that correspond to that filter, and add it to the overall Lots object.

However, this does not work. I am unsure how to fix this. It works fine with just one search criteria, but when I have multiple criteria it does not work.


Solution

  • try this

    if(string.IsNullOrEmpty(businessUnits)) return null;
    
    var buArr =  businessUnits.Split(",");
    
    return _gradingContext.Lots
                .Where(x=> buArr.Contains(x.BusinessUnit))
                .ToList();