2

I am trying to write a c# lambda expression with a dynamic where condition and trying to understand the type of content inside where condition. How can I call that content inside where clause dynamically?

I am taking string here for example

string query1 = "p=>p.id == 1 && p.name==\"abc\" ";
string query2 = "p=>p.id == 2 && p.name==\"def\" ";

//Normal Lambda Expression:
var details = _db.MyTable.Where(p=>p.id == 1 && p.name=="abc")

//Trying to check these if it works 
var details1 = _db.MyTable.Where(query1)

var details2 = _db.MyTable.Where(query2)
6
  • 1
    are you trying to do assignments inside your query? I don't think that will work. Commented May 9, 2018 at 22:10
  • what will be the type inside where clause? How can we dynamically assign clause? Commented May 9, 2018 at 22:11
  • 2
    You might be able to use dynamic linq. Commented May 9, 2018 at 22:12
  • How (and why) did you build that string? Might be better to fix that and go straight to building a Lambda expression. Commented May 9, 2018 at 22:14
  • I am trying to use single lambda expression by change my where condition based on few conditions. Commented May 9, 2018 at 22:17

1 Answer 1

2

Lambda expressions can use variables within their scope, so you can write it as:

int queryId = 1;
string queryName = "abc";
var details = _db.MyTable.Where(p=>p.id == queryId && p.name== queryName);

In this way you could determine what queryID and queryName were dynamically and pass them to the lambda expression. I'm also assuming you intended to check for equality with == rather than assign with =.

Sign up to request clarification or add additional context in comments.

1 Comment

Also: if (queryId != 0) details = details.Where(p=> p.id==queryID); if (!string.IsNullOrEmpty(queryName)) details = details.Where(p => p.name == queryName);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.