Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a user-input string as a field name to access a field within an object?

I'm doing a little bit of search from a database using linq. I have multiple column names like country, name, phone number...

Now I've created a dropdownlist and pass the user selected data as a parameter "searchedField" to my controller method. Now if I take the input of a "country", I expect the code to be

    entries = entries.Where(s => s.country.Contains(searchString));

If user selected "name"

    entries = entries.Where(s => s.name.Contains(searchString));

Excuse me for this rather unreasonable example, since I can always just copy lines and make cases, but I wonder if there is a way to utilize things like reflection to convert string to "code" to access a field?

    String searchedField = "name"

    ...

    entries = entries.Where(s => s.searchedField.Contains(searchString));

This is my first question here, thanks!

like image 485
waltyellow Avatar asked Jun 26 '14 09:06

waltyellow


2 Answers

You can use Dynamic Linq.

entries = entries
    .Where(
        string.Format(
            "{0} = '{1}'",
            searchedField,
            searchString
        )
    );

Note: depending on the type of field you'll need to add quotes, or not.

like image 54
Maarten Avatar answered Oct 01 '22 05:10

Maarten


You can do a reflection lookup (note: I've omitted error checking):

string GetPropertyAsString(object obj, string propertyName)
{
  var propertyInfo - obj.GetType().GetProperty(propertyName);
  return propertyInfo.GetValue(obj).ToString();
}

and then say

entries = entries.Where(s => GetPropertyAsString(s, searchedField).Contains(searchString));
like image 33
Sean Avatar answered Oct 01 '22 07:10

Sean