Skip to content

Instantly share code, notes, and snippets.

@swaters86
Created January 17, 2025 18:05
Show Gist options
  • Save swaters86/ea97f7b6bf6deea82b54d6e794eef3ad to your computer and use it in GitHub Desktop.
Save swaters86/ea97f7b6bf6deea82b54d6e794eef3ad to your computer and use it in GitHub Desktop.
private void FilterDate(FilterDescriptor filter, ref IQueryable<LogWithDetail> query, string columnName)
{
if (!string.IsNullOrEmpty(columnName) && filter.FilterValue != null)
{
// Get the property info for the specified column
var propertyInfo = typeof(LogWithDetail).GetProperty(columnName);
// Ensure the column exists and is of type DateTime
if (propertyInfo != null && propertyInfo.PropertyType == typeof(DateTime))
{
// Parse the filter value into a DateTime object
if (!DateTime.TryParse(filter.FilterValue.ToString(), out DateTime filterDate))
{
throw new ArgumentException($"Invalid date value: {filter.FilterValue}");
}
// Create the parameter for the lambda (e.g., "x")
var parameter = Expression.Parameter(typeof(LogWithDetail), "x");
// Access the dynamic property (e.g., "x.CreatedDate" or "x.LastDate")
var propertyAccess = Expression.Property(parameter, propertyInfo.Name);
// Create the constant for the filter value (e.g., "filterDate")
var constant = Expression.Constant(filterDate, typeof(DateTime));
// Build the comparison expression based on the filter operator
Expression comparison = filter.FilterOperator switch
{
Radzen.FilterOperator.Equals => Expression.Equal(propertyAccess, constant),
Radzen.FilterOperator.NotEquals => Expression.NotEqual(propertyAccess, constant),
Radzen.FilterOperator.GreaterThan => Expression.GreaterThan(propertyAccess, constant),
Radzen.FilterOperator.GreaterThanOrEquals => Expression.GreaterThanOrEqual(propertyAccess, constant),
Radzen.FilterOperator.LessThan => Expression.LessThan(propertyAccess, constant),
Radzen.FilterOperator.LessThanOrEquals => Expression.LessThanOrEqual(propertyAccess, constant),
_ => throw new NotSupportedException($"Unsupported operator: {filter.FilterOperator}")
};
// Combine the comparison into a lambda expression (e.g., "x => x.CreatedDate == filterDate")
var lambda = Expression.Lambda<Func<LogWithDetail, bool>>(comparison, parameter);
// Apply the filter to the query
query = query.Where(lambda);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment