简体   繁体   中英

Advanced Search in LINQ Query

I want to make advanced search (filtering) using different criteria. For example, if first name is available then query should return all the available matches. IF first name and last name both are available then it should match first name or last name and similar way many criteria (gender, profession, education etc.)

Here is my controller Method in which I am taking all the ajax data as parameters.

 [HttpPost]
    public ActionResult Search(string cno, string fname, string lname, string male, string female, string stateid, string cityid, string professionid, string educationid)
    {
        if (Request.IsAjaxRequest())
        {
            var db = new clubDataContext();

            /*----------Advanced Search Query-------------*/

            return PartialView("SerachResult");
        }
        else
            return RedirectToAction("Index", "home");
    }

It may possible that some parameters have null value. So please suggest LINQ Query that is most suitable in this situation.

You have an option to use c# null-coalescing operator

Users.Where(x => x.firstName == (fname??x.firstName) || x.lastName == (lname?? x.lastName)).ToList();

further

Users.Where(x => x.firstName.Contains(fname??x.firstName) || x.lastName.Contains(lname?? x.lastName)).ToList();

Equivalent SQL :

SELECT * FROM User u 
     WHERE u.FirstName = ISNULL(@fname,u.FirstName)
           OR u.LastName = ISNULL(@lname,u.LastName)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM