Expression tree for child collection List<string>.Any - c#

I am building generic linq query using expression tree. I am stuck when creating expression on child collection. Method call blows up because of incompatible types. Normally I know what to put there, but the Any() method call has me confused. I've tried every type I can think of and no luck. Any help would be appreciated.
Here is my entity class:
public class Story : Entity
{
public string Author { get; set; }
public IList<string> Contributors { get; set; }
}
Query for which I want to generate expression tree:
var stories = new List<Story>();
stories.Where(p => p.Author.Contains("Test") || p.Contributors.Any(c => c.Contains("Test")));
What I have got so far
public interface IFilterCriteria
{
string PropertyToCompare { get; set; }
object ValueToCompare { get; set; }
FilterOperator FilterOperator { get; set; }
bool IsList { get; set; }
Expression Expression { get; set; }
}
public static IQueryable<T> Filter<T>(this IQueryable<T> query, IList<IFilterCriteria> filterCriterias, LogicalOperator logicalOperator = LogicalOperator.And)
{
if (filterCriterias != null && filterCriterias.Any())
{
var resultCondition = filterCriterias.ToExpression(query, logicalOperator);
var parameter = Expression.Parameter(query.ElementType, "p");
if (resultCondition != null)
{
var lambda = Expression.Lambda(resultCondition, parameter);
var mce = Expression.Call(
typeof(Queryable), "Where",
new[] { query.ElementType },
query.Expression,
lambda);
return query.Provider.CreateQuery<T>(mce);
}
}
return query;
}
public static Expression ToExpression<T>(this IList<IFilterCriteria> filterCriterias, IQueryable<T> query, LogicalOperator logicalOperator = LogicalOperator.And)
{
Expression resultCondition = null;
if (filterCriterias.Any())
{
var parameter = Expression.Parameter(query.ElementType, "p");
foreach (var filterCriteria in filterCriterias)
{
var propertyExpression = filterCriteria.PropertyToCompare.Split('.').Aggregate<string, MemberExpression>(null, (current, property) => Expression.Property(current ?? (parameter as Expression), property));
Expression valueExpression;
var constantExpression = Expression.Constant(filterCriteria.ValueToCompare);
if (!filterCriteria.IsList)
{
valueExpression = Expression.Convert(constantExpression, propertyExpression.Type);
}
else
{
valueExpression = Expression.Call(typeof (Enumerable), "Any", new[] {typeof (string)},
propertyExpression, filterCriteria.Expression,
Expression.Constant(filterCriteria.ValueToCompare,
typeof (string)));
}
Expression condition;
switch (filterCriteria.FilterOperator)
{
case FilterOperator.IsEqualTo:
condition = Expression.Equal(propertyExpression, valueExpression);
break;
case FilterOperator.IsNotEqualTo:
condition = Expression.NotEqual(propertyExpression, valueExpression);
break;
case FilterOperator.IsGreaterThan:
condition = Expression.GreaterThan(propertyExpression, valueExpression);
break;
case FilterOperator.IsGreaterThanOrEqualTo:
condition = Expression.GreaterThanOrEqual(propertyExpression, valueExpression);
break;
case FilterOperator.IsLessThan:
condition = Expression.LessThan(propertyExpression, valueExpression);
break;
case FilterOperator.IsLessThanOrEqualTo:
condition = Expression.LessThanOrEqual(propertyExpression, valueExpression);
break;
case FilterOperator.Contains:
condition = Expression.Call(propertyExpression, typeof(string).GetMethod("Contains", new[] { typeof(string) }), valueExpression);
break;
case FilterOperator.StartsWith:
condition = Expression.Call(propertyExpression, typeof(string).GetMethod("StartsWith", new[] { typeof(string) }), valueExpression);
break;
case FilterOperator.EndsWith:
condition = Expression.Call(propertyExpression, typeof(string).GetMethod("EndsWith", new[] { typeof(string) }), valueExpression);
break;
default:
condition = valueExpression;
break;
}
if (resultCondition != null)
{
switch (logicalOperator)
{
case LogicalOperator.And:
resultCondition = Expression.AndAlso(resultCondition, condition);
break;
case LogicalOperator.Or:
resultCondition = Expression.OrElse(resultCondition, condition);
break;
}
}
else
{
resultCondition = condition;
}
}
}
return resultCondition;
}
That's how I am using expressions:
var stories = new List<Story>();
var filters = new List<FilterCriteria>();
filter.Add(new FilterCriteria { ValueToCompare = "Test", PropertyToCompare = "Author", FilterOperator = FilterOperator.Contains });
Expression<Func<string, bool>> func = t => t.Contains("Test");
filter.Add(new FilterCriteria { ValueToCompare = "Test", PropertyToCompare = "Contributors", FilterOperator = FilterOperator.Contains, Expression = func });
stories.Filter(filters, LogicalOperator.Or).ToList();
But after running this code, I get this error which I am not able to resolve
No generic method 'Any' on type 'System.Linq.Queryable' is compatible
with the supplied type arguments and arguments. No type arguments
should be provided if the method is non-generic. Description: An
unhandled exception occurred during the execution of the current web
request. Please review the stack trace for more information about the
error and where it originated in the code.
Exception Details: System.InvalidOperationException: No generic method
'Any' on type 'System.Linq.Queryable' is compatible with the supplied
type arguments and arguments. No type arguments should be provided if
the method is non-generic.
Source Error:
Line 184: { Line 185:
var overload = typeof(Queryable).GetMethods().Single(mi => mi.Name ==
"Any" && mi.GetParameters().Count() == 2); Line 186:
Expression.Call(typeof(Queryable), "Any", new[] { typeof(string) },
propertyExpression, or); Line 187:
valueExpression = Expression.Call(typeof(Enumerable), "Any", new[] {
typeof(string)}, propertyExpression, or, Expression.Constant("Test",

You don't call Any method anywhere in your code.
You should extend Contains, example:
case FilterOperator.Contains:
// if collection
if (propertyExpression.Type.IsGenericType &&
typeof(IEnumerable<>)
.MakeGenericType(propertyExpression.Type.GetGenericArguments())
.IsAssignableFrom(propertyExpression.Type))
{
// find AsQueryable method
var toQueryable = typeof(Queryable).GetMethods()
.Where(m => m.Name == "AsQueryable")
.Single(m => m.IsGenericMethod)
.MakeGenericMethod(typeof(string));
// find Any method
var method = typeof(Queryable).GetMethods()
.Where(m => m.Name == "Any")
.Single(m => m.GetParameters().Length == 2)
.MakeGenericMethod(typeof(string));
// make expression
condition = Expression.Call(
null,
method,
Expression.Call(null, toQueryable, propertyExpression),
filterCriteria.Expression
);
}
else
{
condition = Expression.Call(propertyExpression, typeof(string).GetMethod("Contains", new[] { typeof(string) }), valueExpression);
}
break;
Also you should have created one p parameter (Expression.Parameter(query.ElementType, "p")) otherwise you'll get variable 'p' of type 'WpfApplication2.Story' referenced from scope '', but it is not defined error.
You may pass parameter from Filter method to ToExpression method.

Related

Define a generic lambda in C# and assign it to a variable to be used with MakeGenericMethod

I know I can define a generic function and then call it with Type parameters by help of reflection. Something like that:
private static void SomeFunc<Tf>()
{
// Something type safe against Tf
}
public void CallingFunc()
{
var someType = typeof(whatever); // This may be retrieved using reflection as well instead
var someMethod = this.GetType().GetMethod(nameof(SomeFunc)), BindingFlags.Static | BindingFlags.NonPublic);
var typedMethod = someMethod.MakeGenericMethod(someType);
typedMethod.Invoke(null, null);
}
Now, is there a way to declare this SomeMethod<Tf>() inline as a lambda, to avoid declaring it as a separate method in the class, but still being able to use it with MakeGenericMethod? Something like:
public void CallingFunc()
{
var someType = typeof(whatever); // This may be retrieved using reflection as well instead
// This obviously doesn't work as it requires Tf to be known at this stage, and we can have Tf only as a Type variable here => what should I do instead?
var someMethod = new Action<Tf>(() => /* Something type safe against Tf */).Method;
var typedMethod = someMethod.MakeGenericMethod(someType);
typedMethod.Invoke(null, null);
}
Making CallingFunc generic as well is not an option - the someType variable is retrieved with reflection so is not known on compile time.
Based on: https://gist.github.com/afreeland/6733381 thanks !
With a little improve:
public class ExpressionBuilder
{
// Define some of our default filtering options
private static MethodInfo containsMethod = typeof(string).GetMethod("Contains", new[] { typeof(string) });
private static MethodInfo startsWithMethod = typeof(string).GetMethod("StartsWith", new[] { typeof(string) });
private static MethodInfo endsWithMethod = typeof(string).GetMethod("EndsWith", new[] { typeof(string) });
public static Expression<Func<T, bool>> GetExpression(List<GridHelper.Filter> filters)
{
// No filters passed in #KickIT
if (filters.Count == 0)
return null;
// Create the parameter for the ObjectType (typically the 'x' in your expression (x => 'x')
// The "parm" string is used strictly for debugging purposes
ParameterExpression param = Expression.Parameter(typeof(T), "parm");
// Store the result of a calculated Expression
Expression exp = null;
if (filters.Count == 1)
exp = GetExpression<T>(param, filters[0]); // Create expression from a single instance
else if (filters.Count == 2)
exp = GetExpression<T>(param, filters[0], filters[1]); // Create expression that utilizes AndAlso mentality
else
{
// Loop through filters until we have created an expression for each
while (filters.Count > 0)
{
// Grab initial filters remaining in our List
var f1 = filters[0];
var f2 = filters[1];
// Check if we have already set our Expression
if (exp == null)
exp = GetExpression<T>(param, filters[0], filters[1]); // First iteration through our filters
else
exp = Expression.AndAlso(exp, GetExpression<T>(param, filters[0], filters[1])); // Add to our existing expression
filters.Remove(f1);
filters.Remove(f2);
// Odd number, handle this seperately
if (filters.Count == 1)
{
// Pass in our existing expression and our newly created expression from our last remaining filter
exp = Expression.AndAlso(exp, GetExpression<T>(param, filters[0]));
// Remove filter to break out of while loop
filters.RemoveAt(0);
}
}
}
return Expression.Lambda<Func<T, bool>>(exp, param);
}
private static Expression GetExpression<T>(ParameterExpression param, GridHelper.Filter filter)
{
// The member you want to evaluate (x => x.FirstName)
MemberExpression member = Expression.Property(param, filter.PropertyName);
var typeOfValue = filter.Value.GetType();
// The value you want to evaluate
ConstantExpression constant = Expression.Constant(filter.Value, typeOfValue);
// Determine how we want to apply the expression
switch (filter.Operator)
{
case GridHelper.Operator.Equals:
return Expression.Equal(member, constant);
case GridHelper.Operator.NotEqual:
return Expression.Equal(member, constant);
case GridHelper.Operator.Contains:
return Expression.Call(member, containsMethod, constant);
case GridHelper.Operator.GreaterThan:
return Expression.GreaterThan(member, constant);
case GridHelper.Operator.GreaterThanOrEqual:
return Expression.GreaterThanOrEqual(member, constant);
case GridHelper.Operator.LessThan:
return Expression.LessThan(member, constant);
case GridHelper.Operator.LessThanOrEqualTo:
return Expression.LessThanOrEqual(member, constant);
case GridHelper.Operator.StartsWith:
return Expression.Call(member, startsWithMethod, constant);
case GridHelper.Operator.EndsWith:
return Expression.Call(member, endsWithMethod, constant);
}
return null;
}
private static BinaryExpression GetExpression<T>(ParameterExpression param, GridHelper.Filter filter1, GridHelper.Filter filter2)
{
Expression result1 = GetExpression<T>(param, filter1);
Expression result2 = GetExpression<T>(param, filter2);
return Expression.AndAlso(result1, result2);
}
}
// Filter class
public class GridHelper
{
public enum Operator
{
Contains,
GreaterThan,
GreaterThanOrEqual,
LessThan,
LessThanOrEqualTo,
StartsWith,
EndsWith,
Equals,
NotEqual,
Or
}
public class Filter
{
public string PropertyName { get; set; }
public object? Value { get; set; }
public Operator Operator { get; set; }
}
}

how to select multi columns filter with lambda expression

is there a short way,
I don't want to use "if state" for every situation
what do you think
Description : type of query is IQueryable
public class OrderFilter{
public string SearchValue { get => _searchValue.ToLower(); set => _searchValue = value; }
public string[] SearchColumns { get; set; }
}
if (!string.IsNullOrWhiteSpace(orderFilter.SearchValue))
if (orderFilter.SearchColumns.Contains("warehouse"))
query = query.Where(x => x.Warehouse.Description.Contains(orderFilter.SearchValue));
if (orderFilter.SearchColumns.Contains("date"))
query = query.Where(x => x.Date.Contains(orderFilter.SearchValue));
if (orderFilter.SearchColumns.Contains("warehouse") && orderFilter.SearchColumns.Contains("date"))
query = query.Where(x => x.OrderNo.Contains(orderFilter.SearchValue)
|| x.Warehouse.Description.Contains(orderFilter.SearchValue)
|| x.Client.Description.Contains(orderFilter.SearchValue)
|| x.Date.ToString().Contains(orderFilter.SearchValue)
|| x.Salesman.Username.Contains(orderFilter.SearchValue)
);
}
Access nested properties with dynamic lambda using Linq.Expression
found the answer I was looking for
public class LambdaHelper
{
public Expression<Func<TSource, bool>> MultiSearchOrder<TSource>(string[] columns, string value)
{
ParameterExpression parameter = Expression.Parameter(typeof(TSource), "x"); // x=> . ... demektir. parametre
MethodInfo containsMethod = typeof(String).GetMethod("Contains", new Type[] { typeof(String) });
Expression dynamiclambda = null;
MethodCallExpression call = null;
foreach (var propertyName in columns)
{
MemberExpression propertyAccess = NestedExpressionProperty(parameter, propertyName);
call = Expression.Call(propertyAccess, containsMethod, Expression.Constant(value));
if (null == dynamiclambda)
{
dynamiclambda = call;
}
else
{
dynamiclambda = Expression.Or(dynamiclambda, call);
}
}
Expression<Func<TSource, bool>> predicate = Expression.Lambda<Func<TSource, bool>>(dynamiclambda, parameter);
return predicate;
}
private MemberExpression NestedExpressionProperty(Expression expression, string propertyName)
{
string[] parts = propertyName.Split('.');
int partsL = parts.Length;
return (partsL > 1)
?
Expression.Property(
NestedExpressionProperty(
expression,
parts.Take(partsL - 1)
.Aggregate((a, i) => a + "." + i)
),
parts[partsL - 1])
:
Expression.Property(expression, propertyName);
}
I think you add one property (SearchKey) that property contains of all properties value that used for search in writing time and you using this property instead of OR for example :
savingTime: SearhKey="OrderNo.value Warehouse.Description.Value ...."
Searching Time:
if (!string.IsNullOrWhiteSpace(orderFilter.SearchValue))
{
query = query.Where(x =>
x.SearchKey.Contains(orderFilter.SearchValue) );
}
you can do an extension o OrderFilter and reuse it :
public static bool HasAny<TSource>(this OrderFilter filter, IEnumerable<TSource> source)
{
if(filter == null)
throw new ArgumentNullException(nameof(filter));
if(filter.SearchColumns == null)
throw new ArgumentNullException(nameof(filter.SearchColumns));
if(string.IsNullOrWhiteSpace(filter.SearchValue))
throw new ArgumentNullException(nameof(filter.SearchValue));
if(source == null)
throw new ArgumentNullException(nameof(source));
var properties = typeof(TSource).GetProperties().Where(x=> filter.SearchColumns.Any(s=> s.IndexOf(x.Name, StringComparison.InvariantCultureIgnoreCase) > 0));
foreach(var item in source)
{
foreach(var property in properties)
{
var value = property.GetValue(item)?.ToString();
if(value?.Equals(filter.SearchValue , StringComparison.InvariantCultureIgnoreCase) == true)
{
return true;
}
}
}
return false;
}
now you can do this :
var isValueExists = orderFilter.HasAny(query);

Generic Multi-Level Filter for WebApi in C# using Expression Tree, Issue with Nullable Sub Properties

I am making a generic multi-level filter for my WebApi in C#. However i keep getting the following error:
Expression of type 'System.Void' cannot be used for return type 'System.Boolean'
I believe the error happens when a sub property is nullable. For exemple, if i have Entity.SubEntity.description and i filter on description when SubEntity is null, then the error happens. However if the SubEntity is not null, then it works fine.
Other important information:
For the filterDto, the value property can either be an array or a
string.
The error happens when i convert Queryable.ToList() after the return of the Filter function.
Order of calls Filter() -> CompileFilter() -> CompileComparison()
I am not that good with Expression Trees, so i know i am missing some notions here. Any help would be greatly appreciated.
Code Snippet:
public partial class FilterDto
{
public string property { get; set; }
public dynamic value { get; set; }
public string #operator { get; set; }
public bool exactMatch { get; set; }
}
public IQueryable<TEntity> Filter(IQueryable<TEntity> queryable, ICollection<FilterDto> filterDtoCollection, Expression<Func<TEntity, object>> filterProperty)
{
if ((filterDtoCollection == null) || (filterDtoCollection.Count <= 0))
return queryable;
Expression filterExpression = null;
ParameterExpression pe = Expression.Parameter(typeof(TEntity), "x");
Expression ie = GetDeepPropertyExpression(pe, filterProperty.GetMemberName());
Type includePropertyType = filterProperty.Body.Type;
var comparisons = filterDtoCollection.Where(x => includePropertyType.GetProperty(x.property) != null).Select(x => CompileFilter(Expression.Property(ie, x.property), x));
if (comparisons != null && comparisons.Count() > 0)
filterExpression = comparisons.Aggregate((x, y) => Expression.AndAlso(x, y));
else
return queryable;
Func<TEntity, Boolean> expression = Expression.Lambda<Func<TEntity, Boolean>>(filterExpression, pe).Compile();
return queryable.Where(expression).AsQueryable();
}
private Expression CompileFilter(Expression property, FilterDto filterDto)
{
Expression filterExpression = null;
Expression comparison = null;
if (filterDto.value.GetType() != typeof(JArray))
{
filterExpression = CompileComparison(property, filterDto.value, filterDto.#operator, filterDto.exactMatch);
}
else
{
foreach (dynamic filterValue in filterDto.value)
{
dynamic value = Convert.ChangeType(filterValue.Value, property.Type);
comparison = CompileComparison(property, value, filterDto.#operator, filterDto.exactMatch);
if (filterExpression == null)
{
filterExpression = comparison;
}
else
{
if (filterDto.#operator == "in" || filterDto.#operator == "like")
filterExpression = Expression.OrElse(filterExpression, comparison);
else
filterExpression = Expression.AndAlso(filterExpression, comparison);
}
}
}
return filterExpression;
}
private Expression CompileComparison(Expression property, dynamic value, string #operator, bool exactMatch)
{
Expression comparison = null;
Expression constant = Expression.Convert(Expression.Constant(value), property.Type);
MethodInfo method = null;
switch (#operator)
{
case "<":
comparison = Expression.LessThan(property, constant);
break;
case "<=":
comparison = Expression.LessThanOrEqual(property, constant);
break;
case "=":
comparison = Expression.Equal(property, constant);
break;
case ">=":
comparison = Expression.GreaterThanOrEqual(property, constant);
break;
case ">":
comparison = Expression.GreaterThan(property, constant);
break;
case "!=":
comparison = Expression.NotEqual(property, constant);
break;
case "in":
comparison = Expression.Equal(property, constant);
break;
case "like":
if (value.GetType() == typeof(String))
{
method = typeof(ExtensionMethods).GetMethod("Contains");
comparison = Expression.Call(null, method, property, Expression.Constant(value), Expression.Constant(StringComparison.OrdinalIgnoreCase));
}
else
{
comparison = Expression.Equal(property, constant);
}
break;
default:
if (!exactMatch && value.GetType() == typeof(String))
{
method = typeof(ExtensionMethods).GetMethod("Contains");
comparison = Expression.Call(null, method, property, Expression.Constant(value.ToString()), Expression.Constant(StringComparison.OrdinalIgnoreCase));
}
else
{
comparison = Expression.Equal(property, constant);
}
break;
}
return comparison;
}
private Expression GetDeepPropertyExpression(Expression initialInstance, IList<string> property)
{
Expression result = null;
foreach (string propertyName in property)
{
Expression instance = result;
if (instance == null)
instance = initialInstance;
result = Expression.Property(instance, propertyName);
}
return result;
}

How can I make this query work in LINQ to Entities?

I have to following code:
private static bool DoesColValueExist<T>(IQueryable dataToSearchIn, string colName, string colValue)
{
int noOfClients = 1;
Type type = typeof(T);
if (colValue != "" && colName != "")
{
var property = type.GetProperty(colName);
var parameter = Expression.Parameter(type, "p");
var propertyAccess = Expression.MakeMemberAccess(parameter, property);
Expression left = Expression.Call(propertyAccess, typeof(object).GetMethod("ToString", System.Type.EmptyTypes));
left = Expression.Call(left, typeof(string).GetMethod("ToLower", System.Type.EmptyTypes));
Expression right = Expression.Constant(colValue.ToLower(), typeof(string));
MethodInfo method = typeof(string).GetMethod("Equals", new[] { typeof(string) });
Expression searchExpression = Expression.Call(left, method, right);
MethodCallExpression whereCallExpression = Expression.Call(
typeof(Queryable),
"Where",
new Type[] { type },
dataToSearchIn.Expression,
Expression.Lambda<Func<T, bool>>(searchExpression, new ParameterExpression[] { parameter }));
var searchedData = dataToSearchIn.Provider.CreateQuery(whereCallExpression);
noOfClients = searchedData.Cast<T>().Count();
if (noOfClients == 0)
return false;
else
return true;
}
return true;
}
It works with LINQ to SQL but with LINQ to Entities, I get the error:
LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression.
Linq to Entities does not support .ToString() method. I also am not sure if this is a great idea to use string comparison for types that are not strings. But not all is lost. I came up with the following solution:
public partial class MyEntity
{
public int ID { get; set; }
public int Type { get; set; }
public string X { get; set; }
}
public class MyContext : DbContext
{
public DbSet<MyEntity> Entities { get; set; }
}
class Program
{
static void Main(string[] args)
{
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<MyContext>());
using (var ctx = new MyContext())
{
if (!ctx.Entities.Any())
{
ctx.Entities.Add(new MyEntity() { ID = 1, Type = 2, X = "ABC" });
ctx.SaveChanges();
}
Console.WriteLine(DoesColValueExist(ctx.Entities, e => e.X, "aBc"));
Console.WriteLine(DoesColValueExist(ctx.Entities, e => e.X, "aBcD"));
Console.WriteLine(DoesColValueExist(ctx.Entities, e => e.Type, 2));
Console.WriteLine(DoesColValueExist(ctx.Entities, e => e.Type, 5));
}
}
private static bool DoesColValueExist<TEntity, TProperty>(IQueryable<TEntity> dataToSearchIn, Expression<Func<TEntity, TProperty>> property, TProperty colValue)
{
var memberExpression = property.Body as MemberExpression;
if (memberExpression == null || !(memberExpression.Member is PropertyInfo))
{
throw new ArgumentException("Property expected", "property");
}
Expression left = property.Body;
Expression right = Expression.Constant(colValue, typeof(TProperty));
if (typeof(TProperty) == typeof(string))
{
MethodInfo toLower = typeof(string).GetMethod("ToLower", new Type[0]);
left = Expression.Call(left, toLower);
right = Expression.Call(right, toLower);
}
Expression searchExpression = Expression.Equal(left, right);
var lambda = Expression.Lambda<Func<TEntity, bool>>(Expression.Equal(left, right), new ParameterExpression[] { property.Parameters.Single() });
return dataToSearchIn.Where(lambda).Any();
}
}
The nice thing about it is that it is more type safe than string based solution - the value of the parameter has to be the same as the value of the property. The property in turn has to be a member of the entity that is the generic type of the IQueryable'1 passed as the first parameter. Another helpful thing is that when coding against this method intellisense will show you member of the entity when you start typing the lambda expression for the second parameter. In the method itself I added an exception for string type when I call .ToLower() on both property value and the requested value to make the comparison case insensitive. For non-string types the values are compared "as is" i.e. without any modifications.
The example above is complete - you can copy and paste it to a console app project (you need to reference EntityFramework.dll though).
Hope this helps.
Try this:
private static bool DoesColValueExist<T>(IQueryable dataToSearchIn, string colName, string colValue)
{
int noOfClients = 1;
Type type = typeof(T);
if (colValue != "" && colName != "")
{
var property = type.GetProperty(colName);
var parameter = Expression.Parameter(type, "p");
var propertyAccess = Expression.MakeMemberAccess(parameter, property);
Expression left = property.PropertyType == typeof(string) ? propertyAccess : Expression.Call(propertyAccess, typeof(object).GetMethod("ToString", System.Type.EmptyTypes));
left = Expression.Call(left, typeof(string).GetMethod("ToLower", System.Type.EmptyTypes));
Expression right = Expression.Constant(colValue.ToLower(), typeof(string));
MethodInfo method = typeof(string).GetMethod("Equals", new[] { typeof(string) });
Expression searchExpression = Expression.Call(left, method, right);
MethodCallExpression whereCallExpression = Expression.Call(
typeof(Queryable),
"Where",
new Type[] { type },
dataToSearchIn.Expression,
Expression.Lambda<Func<T, bool>>(searchExpression, new ParameterExpression[] { parameter }));
var searchedData = dataToSearchIn.Provider.CreateQuery(whereCallExpression);
noOfClients = searchedData.Cast<T>().Count();
if (noOfClients == 0)
return false;
else
return true;
}
return true;
}
Basically, if the property is string then it doesn't call the ToString() method.
Hope it helps.

How do I specify the Linq OrderBy argument dynamically? [duplicate]

This question already has answers here:
Dynamic LINQ OrderBy on IEnumerable<T> / IQueryable<T>
(24 answers)
Closed 2 years ago.
How do I specify the argument passed to orderby using a value I take as a parameter?
Ex:
List<Student> existingStudends = new List<Student>{ new Student {...}, new Student {...}}
Currently implementation:
List<Student> orderbyAddress = existingStudends.OrderBy(c => c.Address).ToList();
Instead of c.Address, how can I take that as a parameter?
Example
string param = "City";
List<Student> orderbyAddress = existingStudends.OrderByDescending(c => param).ToList();
You can use a little bit of reflection to construct the expression tree as follows (this is an extension method):
public static IQueryable<TEntity> OrderBy<TEntity>(this IQueryable<TEntity> source, string orderByProperty,
bool desc)
{
string command = desc ? "OrderByDescending" : "OrderBy";
var type = typeof(TEntity);
var property = type.GetProperty(orderByProperty);
var parameter = Expression.Parameter(type, "p");
var propertyAccess = Expression.MakeMemberAccess(parameter, property);
var orderByExpression = Expression.Lambda(propertyAccess, parameter);
var resultExpression = Expression.Call(typeof(Queryable), command, new Type[] { type, property.PropertyType },
source.Expression, Expression.Quote(orderByExpression));
return source.Provider.CreateQuery<TEntity>(resultExpression);
}
orderByProperty is the Property name you want to order by and if pass true as parameter for desc, will sort in descending order; otherwise, will sort in ascending order.
Now you should be able to do existingStudents.OrderBy("City",true); or existingStudents.OrderBy("City",false);
Here's a possiblity using reflection...
var param = "Address";
var propertyInfo = typeof(Student).GetProperty(param);
var orderByAddress = items.OrderBy(x => propertyInfo.GetValue(x, null));
To expand on the answer by #Icarus: if you want the return type of the extension method to be an IOrderedQueryable instead of an IQueryable, you can simply cast the result as follows:
public static IOrderedQueryable<TEntity> OrderBy<TEntity>(this IQueryable<TEntity> source, string orderByProperty, bool desc)
{
string command = desc ? "OrderByDescending" : "OrderBy";
var type = typeof(TEntity);
var property = type.GetProperty(orderByProperty);
var parameter = Expression.Parameter(type, "p");
var propertyAccess = Expression.MakeMemberAccess(parameter, property);
var orderByExpression = Expression.Lambda(propertyAccess, parameter);
var resultExpression = Expression.Call(typeof(Queryable), command, new Type[] { type, property.PropertyType },
source.Expression, Expression.Quote(orderByExpression));
return (IOrderedQueryable<TEntity>)source.Provider.CreateQuery<TEntity>(resultExpression);
}
1) Install System.Linq.Dynamic
2) Add the following code
public static class OrderUtils
{
public static string ToStringForOrdering<T, TKey>(this Expression<Func<T, TKey>> expression, bool isDesc = false)
{
var str = expression.Body.ToString();
var param = expression.Parameters.First().Name;
str = str.Replace("Convert(", "(").Replace(param + ".", "");
return str + (isDesc ? " descending" : "");
}
}
3) Write your switch for selecting of Lambda function
public static class SortHelper
{
public static Expression<Func<UserApp, object>> UserApp(string orderProperty)
{
orderProperty = orderProperty?.ToLowerInvariant();
switch (orderProperty)
{
case "firstname":
return x => x.PersonalInfo.FirstName;
case "lastname":
return x => x.PersonalInfo.LastName;
case "fullname":
return x => x.PersonalInfo.FirstName + x.PersonalInfo.LastName;
case "email":
return x => x.Email;
}
}
}
4) Use your helpers
Dbset.OrderBy(SortHelper.UserApp("firstname").ToStringForOrdering())
5) You can use it with pagging (PagedList)
public virtual IPagedList<T> GetPage<TOrder>(Page page, Expression<Func<T, bool>> where, Expression<Func<T, TOrder>> order, bool isDesc = false,
params Expression<Func<T, object>>[] includes)
{
var orderedQueryable = Dbset.OrderBy(order.ToStringForOrdering(isDesc));
var query = orderedQueryable.Where(where).GetPage(page);
query = AppendIncludes(query, includes);
var results = query.ToList();
var total = Dbset.Count(where);
return new StaticPagedList<T>(results, page.PageNumber, page.PageSize, total);
}
Explanation
System.Linq.Dynamic allows us to set string value in OrderBy method. But inside this extension the string will be parsed to Lambda. So I thought it would work if we will parse Lambda to string and give it to OrderBy method. And it works!
Here's something I came up with for dealing with a conditional Descending. You could combine this with other methods of generating the keySelector func dynamically.
public static IOrderedQueryable<TSource> OrderBy<TSource, TKey>(this IQueryable<TSource> source,
System.Linq.Expressions.Expression<Func<TSource, TKey>> keySelector,
System.ComponentModel.ListSortDirection sortOrder
)
{
if (sortOrder == System.ComponentModel.ListSortDirection.Ascending)
return source.OrderBy(keySelector);
else
return source.OrderByDescending(keySelector);
}
Usage:
//imagine this is some parameter
var direction = System.ComponentModel.ListSortDirection.Ascending;
query = query.OrderBy(ec => ec.MyColumnName, direction);
Notice this allows you to chain this .OrderBy extension with a new parameter onto any IQueryable.
// perhaps passed in as a request of user to change sort order
// var direction = System.ComponentModel.ListSortDirection.Ascending;
query = context.Orders
.Where(o => o.Status == OrderStatus.Paid)
.OrderBy(ec => ec.OrderPaidUtc, direction);
private Func<T, object> GetOrderByExpression<T>(string sortColumn)
{
Func<T, object> orderByExpr = null;
if (!String.IsNullOrEmpty(sortColumn))
{
Type sponsorResultType = typeof(T);
if (sponsorResultType.GetProperties().Any(prop => prop.Name == sortColumn))
{
System.Reflection.PropertyInfo pinfo = sponsorResultType.GetProperty(sortColumn);
orderByExpr = (data => pinfo.GetValue(data, null));
}
}
return orderByExpr;
}
public List<T> OrderByDir<T>(IEnumerable<T> source, string dir, Func<T, object> OrderByColumn)
{
return dir.ToUpper() == "ASC" ? source.OrderBy(OrderByColumn).ToList() : source.OrderByDescending(OrderByColumn).ToList();``
}
// Call the code like below
var orderByExpression= GetOrderByExpression<SearchResultsType>(sort);
var data = OrderByDir<SponsorSearchResults>(resultRecords, SortDirectionString, orderByExpression);
This doesn't let you pass a string, as you asked for in your question, but it might still work for you.
The OrderByDescending method takes a Func<TSource, TKey>, so you can rewrite your function this way:
List<Student> QueryStudents<TKey>(Func<Student, TKey> orderBy)
{
return existingStudents.OrderByDescending(orderBy).ToList();
}
There are other overloads for OrderByDescending as well that take a Expression<Func<TSource, TKey>>, and/or a IComparer<TKey>. You could also look into those and see if they provide you anything of use.
The only solution that worked for me was posted here https://gist.github.com/neoGeneva/1878868 by neoGeneva.
I will re-post his code because it works well and I wouldn't want it to be lost in the interwebs!
public static IQueryable<T> OrderBy<T>(this IQueryable<T> source, string sortExpression)
{
if (source == null)
throw new ArgumentNullException("source", "source is null.");
if (string.IsNullOrEmpty(sortExpression))
throw new ArgumentException("sortExpression is null or empty.", "sortExpression");
var parts = sortExpression.Split(' ');
var isDescending = false;
var propertyName = "";
var tType = typeof(T);
if (parts.Length > 0 && parts[0] != "")
{
propertyName = parts[0];
if (parts.Length > 1)
{
isDescending = parts[1].ToLower().Contains("esc");
}
PropertyInfo prop = tType.GetProperty(propertyName);
if (prop == null)
{
throw new ArgumentException(string.Format("No property '{0}' on type '{1}'", propertyName, tType.Name));
}
var funcType = typeof(Func<,>)
.MakeGenericType(tType, prop.PropertyType);
var lambdaBuilder = typeof(Expression)
.GetMethods()
.First(x => x.Name == "Lambda" && x.ContainsGenericParameters && x.GetParameters().Length == 2)
.MakeGenericMethod(funcType);
var parameter = Expression.Parameter(tType);
var propExpress = Expression.Property(parameter, prop);
var sortLambda = lambdaBuilder
.Invoke(null, new object[] { propExpress, new ParameterExpression[] { parameter } });
var sorter = typeof(Queryable)
.GetMethods()
.FirstOrDefault(x => x.Name == (isDescending ? "OrderByDescending" : "OrderBy") && x.GetParameters().Length == 2)
.MakeGenericMethod(new[] { tType, prop.PropertyType });
return (IQueryable<T>)sorter
.Invoke(null, new object[] { source, sortLambda });
}
return source;
}
Add the nugget package Dynamite to your code
Add the namespace Dynamite.Extensions
Eg : using Dynamite.Extensions;
Give Order by query like any SQL query
Eg : students.OrderBy(" City DESC, Address").ToList();
To extend the response of #Icarus: if you want to sort by two fields I could perform the following function (for one field the response of Icarius works very well).
public static IQueryable<T> OrderByDynamic<T>(this IQueryable<T> q, string SortField1, string SortField2, bool Ascending)
{
var param = Expression.Parameter(typeof(T), "p");
var body = GetBodyExp(SortField1, SortField2, param);
var exp = Expression.Lambda(body, param);
string method = Ascending ? "OrderBy" : "OrderByDescending";
Type[] types = new Type[] { q.ElementType, exp.Body.Type };
var mce = Expression.Call(typeof(Queryable), method, types, q.Expression, exp);
return q.Provider.CreateQuery<T>(mce);
}
This is the function that the body returns for the lambda expression, it works with string and int, but it is enough to add more types to make it work according to the need of each programmer
public static NewExpression GetBodyExp(string field1, string field2, ParameterExpression Parametro)
{
// SE OBTIENE LOS NOMBRES DE LOS TIPOS DE VARIABLE
string TypeName1 = Expression.Property(Parametro, field1).Type.Name;
string TypeName2 = Expression.Property(Parametro, field2).Type.Name;
// SE DECLARA EL TIPO ANONIMO SEGUN LOS TIPOS DE VARIABLES
Type TypeAnonymous = null;
if (TypeName1 == "String")
{
string var1 = "0";
if (TypeName2 == "Int32")
{
int var2 = 0;
var example = new { var1, var2 };
TypeAnonymous = example.GetType();
}
if (TypeName2 == "String")
{
string var2 = "0";
var example = new { var1, var2 };
TypeAnonymous = example.GetType();
}
}
if (TypeName1 == "Int32")
{
int var1 = 0;
if (TypeName2 == "Int32")
{
string var2 = "0";
var example = new { var1, var2 };
TypeAnonymous = example.GetType();
}
if (TypeName2 == "String")
{
string var2 = "0";
var example = new { var1, var2 };
TypeAnonymous = example.GetType();
}
}
//se declaran los TIPOS NECESARIOS PARA GENERAR EL BODY DE LA EXPRESION LAMBDA
MemberExpression[] args = new[] { Expression.PropertyOrField(Parametro, field1), Expression.PropertyOrField(Parametro, field2) };
ConstructorInfo CInfo = TypeAnonymous.GetConstructors()[0];
IEnumerable<MemberInfo> a = TypeAnonymous.GetMembers().Where(m => m.MemberType == MemberTypes.Property);
//BODY
NewExpression body = Expression.New(CInfo, args, TypeAnonymous.GetMembers().Where(m => m.MemberType == MemberTypes.Property));
return body;
}
to use it the following is done
IQueryable<MyClass> IqMyClass= context.MyClass.AsQueryable();
List<MyClass> ListMyClass= IqMyClass.OrderByDynamic("UserName", "IdMyClass", true).ToList();
if there is a better way to do this, it would be great if they share it
I managed to solve it thanks to: How can I make a Multiple property lambda expression with Linq
New Answer : this is a more complete answer that supports multiple columns for order by like SQL. Example : .OrderBy("FirstName,Age DESC") :
namespace Utility;
public static class QueryExtension
{
public static IQueryable<TEntity> OrderBy<TEntity>(this IQueryable<TEntity> source, string orderByProperty, bool desc, bool isThenBy = false)
{
string command = isThenBy ? (desc ? "ThenByDescending" : "ThenBy") : (desc ? "OrderByDescending" : "OrderBy");
var type = typeof(TEntity);
var property = type.GetProperty(orderByProperty);
var parameter = Expression.Parameter(type, "p");
var propertyAccess = Expression.MakeMemberAccess(parameter, property);
var orderByExpression = Expression.Lambda(propertyAccess, parameter);
var resultExpression = Expression.Call(typeof(Queryable), command, new Type[] { type, property.PropertyType },
source.Expression, Expression.Quote(orderByExpression));
return source.Provider.CreateQuery<TEntity>(resultExpression);
}
public static IQueryable<TEntity> OrderBy<TEntity>(this IQueryable<TEntity> source, string sqlOrderByList)
{
var ordebyItems = sqlOrderByList.Trim().Split(',');
IQueryable<TEntity> result = source;
bool useThenBy = false;
foreach (var item in ordebyItems)
{
var splt = item.Trim().Split(' ');
result = result.OrderBy(splt[0].Trim(), (splt.Length > 1 && splt[1].Trim().ToLower() == "desc"), useThenBy);
if (useThenBy)
useThenBy = true;
}
return result;
}
}
The second function iterates over orderby columns and uses the first one.
Use it like this :
using Utility;
...
public void MyMethod()
{
var query = _dbContext.Person.AsQueryable();
query.OrderBy("FirstName,Age DESC");
}
I'm way late to the party but none of these solutions worked for me. I was eager to try System.Linq.Dynamic, but I couldn't find that on Nuget, maybe depreciated? Either way...
Here is a solutions I came up with. I needed to dynamically use a mixture of OrderBy, OrderByDescending and OrderBy > ThenBy.
I simply created an extension method for my list object, a bit hacky I know... I wouldn't recommend this if it were something I was doing a lot of, but it's good for a one off.
List<Employee> Employees = GetAllEmployees();
foreach(Employee oEmployee in Employees.ApplyDynamicSort(eEmployeeSort))
{
//do stuff
}
public static IOrderedEnumerable<Employee> ApplyDynamicSort(this List<Employee> lEmployees, Enums.EmployeeSort eEmployeeSort)
{
switch (eEmployeeSort)
{
case Enums.EmployeeSort.Name_ASC:
return lEmployees.OrderBy(x => x.Name);
case Enums.EmployeeSort.Name_DESC:
return lEmployees.OrderByDescending(x => x.Name);
case Enums.EmployeeSort.Department_ASC_Salary_DESC:
return lEmployees.OrderBy(x => x.Department).ThenByDescending(y => y.Salary);
default:
return lEmployees.OrderBy(x => x.Name);
}
}

Categories