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!
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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With