Skip to content

Instantly share code, notes, and snippets.

@timhobbs
Created November 16, 2012 01:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timhobbs/4083007 to your computer and use it in GitHub Desktop.
Save timhobbs/4083007 to your computer and use it in GitHub Desktop.
An extension method for Telerik MVC grid filtering
///<remarks>
/// Turns out this wasn't needed - and far less elegant than the existing extension method.
/// However, it is still an example of a generic way to match a given property with a value
/// and how to select that property by name (string) and compare its value to the value
/// that is passed in. It works...
///</remarks>
public static IList<T> ApplyFilter<T>(this IList<T> list, FilterDescriptor filter) {
// We wont allow filtering on anything but string type properties
if (filter.MemberType != typeof(string)) throw new ArgumentException("Filtering is only allowed for properties with a type of 'string'.");
var value = filter.Value.ToString();
switch (filter.Operator) {
case FilterOperator.IsEqualTo:
list = list.Where(x => {
var propertyValue = x.GetType().GetProperty(filter.Member).GetValue(x, null);
return String.Equals((string)propertyValue, value, StringComparison.InvariantCultureIgnoreCase);
}).ToList();
break;
case FilterOperator.IsNotEqualTo:
list = list.Where(x => {
var propertyValue = x.GetType().GetProperty(filter.Member).GetValue(x, null);
return String.Equals((string)propertyValue, value, StringComparison.InvariantCultureIgnoreCase) == false;
}).ToList();
break;
case FilterOperator.StartsWith:
list = list.Where(x => {
var propertyValue = x.GetType().GetProperty(filter.Member).GetValue(x, null);
return ((string)propertyValue).StartsWith(value, StringComparison.InvariantCultureIgnoreCase);
}).ToList();
break;
case FilterOperator.Contains:
list = list.Where(x => {
var propertyValue = x.GetType().GetProperty(filter.Member).GetValue(x, null);
return ((string)propertyValue).IndexOf(value, StringComparison.InvariantCultureIgnoreCase) > -1;
}).ToList();
break;
case FilterOperator.EndsWith:
list = list.Where(x => {
var propertyValue = x.GetType().GetProperty(filter.Member).GetValue(x, null);
return ((string)propertyValue).EndsWith(value, StringComparison.InvariantCultureIgnoreCase);
}).ToList();
break;
}
return list;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment