Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# string concatenation in Lambda expression

String qry = "p => p.Title == "Test" && P.Status=0;

myProjects = dataAccessHelper.GetMyDetails(id).
  Where(Append qry string here).ToList();

I am trying to append my query string output to where in Lambda expression. It works fine if I take

myProjects = dataAccessHelper.GetMyDetails(id).
  Where(p => p.Title == "Test" && P.Status=0).ToList(); 

But not like this

myProjects = dataAccessHelper.GetMyDetails(id).
  Where("+ qry +").ToList();

How can I concatenate this and make lambda expression work.

My Controller code

   [HttpGet]
        public virtual ActionResult MyProjects(int? id, string qry)
        {
            var dataAccessHelper = new DataAccessHelper(true);
            IList<ProjectEntity> myProjects;
            if (qry == null)
            {
                myProjects = dataAccessHelper.GetMyProjects(id);
            }
            else
            {
                Expression<Func<ProjectEntity, bool>> expr = qry;
                myProjects = dataAccessHelper.GetMyProjects(id).Where(expr).ToList();

            }

            var myProjectsViewModel = new MyProjectsViewModel() { GetMyProjects =                  myProjects };
            return View(myProjectsViewModel);

        }
like image 593
Kurkula Avatar asked Dec 27 '13 23:12

Kurkula


Video Answer


2 Answers

What you are looking for is a Function Expression. You will need the type for the Where clause, I am going to assume that your type is Project.

If you are using linq to sql you will need to construct an Expression

//assuming Project is type
Expression<Func<Project, bool>> expr = p => p.Title == "Test" && p.Status == 0;

If you are using linq to objects then you can omit the Expression

//assuming Project is type
Func<Project, bool> expr = p => p.Title == "Test" && p.Status == 0;

Now you can use this in your where clause

myProjects = dataAccessHelper.GetMyDetails(id).Where(expr).ToList();

edit

With regards to your edit. You can't really pass in a string to do this with. Your best bet would be to pass in the "Test" and the integer for status, and then put those into the expression.

public virtual ActionResult MyProjects(int? id, string title = "Title", int status = 0)

and then

Func<Project, bool> expr = p => p.Title == title && p.Status == status;
like image 50
Travis J Avatar answered Sep 25 '22 13:09

Travis J


For converting strings to expressions, you will need to do some form of dynamic compilation. This blog post contains some options for doing this:

http://jp-labs.blogspot.com/2008/11/dynamic-lambda-expressions-using.html

like image 43
Corey Ross Avatar answered Sep 23 '22 13:09

Corey Ross