I'm looking for way to get something like this:
string _col1 = "first name";
string _name;
var query = from c in ctx.Customers select c;
_name = query.FirstOrDefault().[_name];
As far as I can see I can only get strongly typed field names but I would like to provide them as string variables.
You need to use reflection for this. If you are trying to filter by a dynamicly selected column, you can try something like this:
string propertyName
string keyword
ParameterExpression parameter = Expression.Parameter(typeof(YourType), "x");
Expression property = Expression.Property(parameter, propertyName);
Expression target = Expression.Constant(keyword);
Expression containsMethod = Expression.Call(property, "Contains", null, target);
Expression<Func<YourType, bool>> lambda =
Expression.Lambda<Func<YourType, bool>>(containsMethod, parameter);
var companies = repository.AsQueryable().Where(lambda);
I what you are trying to do is selecting a particular column, then you can use the same principle for generating the lamba expression and using it in the select (minus the condition)
var companies = repository.AsQueryable().Where(whatever).Select(lambda);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With