An extension method for Telerik MVC grid filtering
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
///<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