There is a data set as IEnumerable<T> GridData
which is bound to a data grid. In one scenario data loaded with T
as Dictionary<string, object>
. When user apply filter/sort on the grid, I can get those as follows.
filters : [{Property: 'abc', Value: 'aaa'}]
sort: [{Property: 'abc'}]
on the Dictionary<string, object>
Key
represent the Property
and Value
represent the Value
.
I'm stuck with filtering and sorting on IEnumerable<T> GridData
. Can anyone show me the direction?
CodePudding user response:
I would go for a helper function like this
private static object GetPropValue(object src, string propName)
{
return src.GetType().GetProperty(propName)?.GetValue(src, null);
}
then filter the GridData like this asuming the filters is an array you need to check against all filters on it.
private static void test<T>(IEnumerable<T> GridData, Dictionary<string, object> filters)
{
IEnumerable<T> result = GridData;
foreach (KeyValuePair<string, object> filter in filters.ToList())
{
result = result.Where(x =>
(x as Dictionary<string, object>).Values.Any(d =>
filter.Value.Equals((T)GetPropValue(d, filter.Key))));
}
}
IF your filters arent a Dictionary, only a List of Tuples<string, object>:
private static void test2<T>(IEnumerable<T> GridData, List<Tuple<string, object>> filters)
{
IEnumerable<T> result = GridData;
foreach (Tuple<string, object> filter in filters.ToList())
{
result = result.Where(x =>
(x as Dictionary<string, object>).Values.Any(d =>
filter.Item2.Equals((T)GetPropValue(d, filter.Item1))));
}
}
And do the sort using the same aproach