I'm trying to write a generic Filter extension method for a system, such that I can call filter on any List and pass in a Dictionary of field names and their values to filter on.
I currently have a method for each type in my system, but I'm trying to consolidate to one method.
Here is what I have so far...simplified so it's only text searching:
public static List<T> Filter<T>(this List<T> model, string json)
{
JavaScriptSerializer ser = new JavaScriptSerializer();
Dictionary<string, object> searchFields = (Dictionary<string, object>)ser.DeserializeObject(json);
foreach (var key in searchFields.Keys)
{
// How do I perform the search?
}
return model;
}
My current filter is a switch statement over each key and checking each field as follows:
switch(key)
{
case "Description":
list = list.Where(x => x.Description.ToLower().Contains(searchFields[key].ToString().ToLower())).ToList();
break;
}
How do I access the property on the generic object to filter it? I assume I need reflection somehow, but I don't know the syntax.
I'm looking for something like:
list = list.where(listobject.getField(key).contains(value))
Is this possible? Thanks in advance for your help!
try something like that inside your foreach
loop
model.Where(m => typeof(T).GetProperty(key).GetValue(m, null)==searchFields[key]);
foreach (var key in searchFields.Keys)
{
model.Where(m => typeof(T).GetProperty(key).GetValue(m, null).Equals(SearchFields[key], StringComparison.OrdianlIgnoreCase);
}
return model.ToList();
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.