Search code examples
linqasp.net-coreblazor

Create a Search function in Blazor that looks up multiple entries in SQL


Apologies i cant provide the actual code for various reasons.

But i am trying to create a search function for multiple entries in a class

example

I have an Implemented task

public async Task<List<RequestList>> SearchRequestAsync(string searchItem)
{
  return await context.RequestLists.Where(s => s.RequestName.ToString().Contains(searchItem)).ToListAsync();
}

RequestName is one of the values in my Database

This works for that column, but i want to filter by multiple columns.

For context i am very new to this and am building and learning as i go.

In essence i tried to see if i could add the values in the RequestList List to another private List, but couldn't figure out how.


Solution

  • You can compose queries in Linq. I think what you want is something like:

    public async Task<List<RequestList>> SearchRequestAsync(string? searchItem1, string? searchItem2 )
    {
      var query = context.RequestLists;
    
      if (searchItem1 is not null)
      {
        query = query.Where(s => s.RequestName.ToString().Contains(searchItem1));
      }
    
      if (searchItem2 is not null)
      {
        query = query.Where(s =>  /* some other condition */ );
      }
    
      return await query.ToListAsync();
    }
    

    multiple Where() clauses operate in series, so they are AND-ed together.