1

C# How To Pass Linq Lambda Parameters to SwitchExpression And Return Expression To .Where(...) Lambda Linq Queryable

i write a linq Lambda query that Who i want use Func That Declare SwitchExpression in this And Use On where(p=>...) in this code use predicat , It's like this :

model is :

public class FieldValue
    {
        public virtual int Id { get; set; }
        public virtual string Value { get; set; }
        public virtual int FieldId_fk { get; set; }
        public virtual int TAdvertiesId_fk { get; set; }
    }

var predicateItemTest = LinqKit.PredicateBuilder.True<FieldValue>().And(x => x.FieldId_fk == 2); //2 is digit for test
SwitchCase[] cases = new SwitchCase[] {
new SwitchCase[] { Expression.SwitchCase(Expression.Constant(predicateItemTest), Expression.Constant(2, typeof(int))) } 
};

SwitchExpression _SwitchExpression = Expression.Switch(Value, Expression.Constant(LinqKit.PredicateBuilder.False<FieldValue>()), //Default Value
 cases);

SwitchCase_Predicate = Expression.Lambda<Func<int, Expression<Func<FieldValue, bool>>>>(_SwitchExpression, Value).Compile();

1) First Test :

var FilterResult = _FieldValue.Table.Where(p=>SwitchCase_Predicate(p.FieldId_fk).Compile()).ToList();

when call this method and who i want pass parameter to SwitchCase_Predicate(...) it has error because Return Type Is expression and should not pass Dynamic parameters. if use like below worked but not allow pass parameter in .where(...) :

2) Second Test :

var FilterResult = _FieldValue.Table.Where(SwitchCase_Predicate(2).Compile()).ToList();

how to pass parameter in where(...) like "First Test" and return expression predicat for use in .where(...) correctly

Please help fix this problem.

  • not be work this solution, i change my solution, in fact we should develop simple code and func in func is not good response for this problem – Rasoul Harouni Feb 14 '21 at 16:16

0 Answers0