Search code examples
linqdynamicwhere-clausenamevaluecollection

How to create a dynamic where clause using a name value collection?


I have column search filter values sent to my web api and I can't figure how to make the where clause dynamic?

Look below (too much code)!!

Name Value Collection:

  public DataTablePager<AccountDTO> Get([FromUri] DataTableParameter param)
        {
            NameValueCollection nvc = HttpUtility.ParseQueryString(Request.RequestUri.Query);

Casting the search values:

if (!String.IsNullOrEmpty(nvc["sSearch_0"]) && !int.TryParse(nvc["sSearch_0"], out tmpInt) ||
                !String.IsNullOrEmpty(nvc["sSearch_1"]) && !int.TryParse(nvc["sSearch_1"], out tmpInt) ||
                !String.IsNullOrEmpty(nvc["sSearch_10"]) && !int.TryParse(nvc["sSearch_10"], out tmpInt)

Setup Where Clause:

filteredresults = filteredresults.Where(i => CorrectNumericTypes
                                                      && (Lead_ID == null || i.Lead_ID == Lead_ID)
                                                      && (Account_ID == null || i.Account_ID == Account_ID)

Solution

  • Here's what I needed (predicate): http://www.c-sharpcorner.com/UploadFile/c42694/dynamic-query-in-linq-using-predicate-builder/