Pass in a field name at run time using Dynamic LINQ library?

asp.net-mvc c# dynamic-linq

Question

This is a small application used on a company intranet by 4 people at the most, and I am new to C# and .NET, so the solution does not have to be grandiose.

I am trying to create a search field for simple .NET C.R.U.D app where the user can pick a category they wish to search from (such as Application Name, or Manager) and then a text-box where they can filter the results based on that field name. The items in the drop down menu are the class field members and I would like for all of them to be searchable. I'm using the Dynamic Linq Library to create a string so that I can pass the column name at run-time but for some reason my queries return no results.

Here is my current query

dr_details = dr_details.Where("@0 == @1",searchType, searchString);

So for instance, searchType & searchString get their values from the query string (We'll say "Manager" and "Joe", respectively) so that the query should be substituted as:

dr_details = dr_details.Where("Manager == Joe");

this gives me no results. However if I hard code the string "Manager == Joe" into the query runs fine.

Any suggestions? This problem would make me yank out my hair if it was long enough! :p

1
0
6/20/2014 7:55:39 PM

Accepted Answer

You don't necessarily have to use dynamic linq for this if you don't want.

Try something like this:

var query = myList.AsQueryable();

switch(searchType)
{
     case "Manger":
        query = query.where(x=> x.Manager == searchString);
        break;
     case "....":
        break;
     default:
        // No search type match in string... an exception? your call
        break;
}

I find this more intuitive since it "builds" the query as it goes...

Edit:

If that is too painful try following this post

-1
5/23/2017 12:21:40 PM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow