none
Link Dynamic Expression Confusion (Need Help) RRS feed

  • Question

  • Consider the following class:

                class Person
                {
                    public string LastName { get; set; }
                    public string FirstName { get; set; }
                    public string MiddleInitial { get; set; }
                    public DateTime StartDate { get; set; }
                    public bool IsActive { get; set; }
                }

    Consider we have in code a default query that is hard coded like so:

     var query = People
                    .Where(d => d.IsActive == true)
                    .Where(d => d.StartDate > DateTime.Now.AddMonths(-1));


    Now, this query eventually is bound to a grid using a .ToList() against this query.  We use an advanced grid (Syncfusion) that allows users to create filters at runtime.  For example a user may apply a LastName filter where it equals "Smith".  At runtime I'm able to see the field name "LastName" as a string and that it is equal to another string "Smith".  At this point I want to take the default query above and expand upon it using what I know at runtime.  The problem is I can't just write the following:

    var modifiedQuery = query.Where( d=>d.filteredFieldName == filteredValue );

    I've read over many of the dynamic expression articles but none of them address how to dynamically set the PropertyName at runtime using the Linq.Expression functions.  Can someone please help me figure this out?  I don't want to have to write a separate expression for every field name possible.  We have several views that need to act in the same manner and we will not know at design time what filters to create expressions for.

    Thanks,

    -Jeff



    I wish I could program in theory. Everything works there.

    Tuesday, July 14, 2015 8:47 PM

Answers

  • Hi Jeff,

    >>The problem is I can't just write the following:

    var modifiedQuery = query.Where( d=>d.filteredFieldName == filteredValue )

    Based on your description, Here I created a demo for you, there is no error or exception throw with your code. And I can query the resulut successfully. The following code work fine.

    Please check my sceenshot.


     Please enlarge this picture that you can see clearly.

    Have a nice day!

    Kristin


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Thursday, July 16, 2015 3:12 AM