Dynamically select property in linq
I have a property whose name is in a variable ( userFilters.property
), which can be of type string / enum / number.
I want to dynamically select different values ββfor this property. how to do it.
var query = CreatePincodeQuery(useFilters);
//userFilters.property contains the property to be selected
Expression<Func<PincodeData, string>> selectExpr = null;
IList<string> list = query.Select(selectExpr)
.Distinct()
.OrderBy(selectExpr)
.ToList();
return list.;
I need to create an expression of a type Expression<Func<PincodeData, string>> selectExpr
to use as part of the select and orderBy block.
How should I do it?
I have reviewed the suggested solution here , here and here , but am not able to figure out how I can change the ones that suit my needs.
EDIT
came up solution below as expected its not working and how to convert value to string.
Func<TEntity, string> CreateNewStatement<TEntity>(string field)
{
///questions/155910/linq-dynamic-select
var xParameter = Expression.Parameter(typeof(TEntity), "o");
var property = Expression.Property(xParameter, typeof(TEntity).GetProperty(field));
var lambda = Expression.Lambda<Func<TEntity, string>>(property, xParameter);
return lambda.Compile();
}
EDIT
I changed the type from string to object but its still unable to create lambda for enum types which could be the reason
source to share
No one has answered this question yet
See similar questions:
or similar: