Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Filter query with multiple optional parameters

I need to write a LINQ Query against a returned list that takes in multiple optional parameters. There will be the following variables:

plan, Id, FirstName, LastName, DateFrom, DateTo, MemDateOfBirth

I want to return a filtered list back via LINQ using these parameters, but all of them are optional. At least one will be supplied when the user hits the search button, but that will be up to the user to decide what they want to search by. If they supply more than 1, I need to filter by all methods they supply...

So for instance, if they supply a first name and to and from dates, I want to return a filtered list of all instances for a person by that first name between the to and from dates, etc...

What is the easiest way to accomplish this with LINQ? These variables are optional parameters, so any or all of them could be supplied. I know I could return the main list, then filter through it multiple times to get the results, but I was wondering if there was a quicker, easier way to do it via LINQ...

thanks in advance for your help!

like image 312
MattE Avatar asked Dec 20 '16 21:12

MattE


1 Answers

i found this to be the simplest way to solve this type of problem

var q = from mt in myTable
        where (mt.FIrstname == FirstNameparam || FirstNameparam == null)
        && (mt.lastname == lastnameParam || lastnameParam == null)
        && (mt.DateField == DateParam || DateParam == null)
        select new
        {
            mt.FIrstname,
            mt.lastname,
            mt.DateField
        };
like image 109
boruchsiper Avatar answered Oct 22 '22 00:10

boruchsiper