Dynamic LINQ with data objects

So, I was looking for a simple example, hopefully a simple problem.

I have a simple List of ListTest (List) object

public class ListTest{
{
    public string perName { get; set; }
    public string perSex { get; set; }
    public ListTest(string pName, string pSex)
    {
        this.perSex = pSex;
        this.perName = pName;
    }
}

I downloaded it with some data:

        List<ListTest> tryIt = new List<ListTest>();
        tryIt.Add(new ListTest("Karen", "F"));
        tryIt.Add(new ListTest("Kate", "F"));
        tryIt.Add(new ListTest("Glen", "M"));
        tryIt.Add(new ListTest("Tiger", "M"));
        tryIt.Add(new ListTest("Clementine", "F"));
        tryIt.Add(new ListTest("Magnolia", "F"));

Now I want to query it using a Lambda expression:

        var things = tryIt
                     .Where(sex => (sex.perSex == "F"))
                     .OrderBy(sex => sex.perName);

But I want to do this dynamically, just in case I want to change my place to "perName".

I can create a Lambda Expression expression for my expressions, but I cannot figure out how to take it through the target line and actually assign it a where clause and execute it.

        IQueryable<ListTest> iq = tryIt.AsQueryable();
        ParameterExpression pe = Expression.Parameter(typeof(ListTest), "Person");
        Expression paEx = Expression.Property(pe, "perSex");
        Expression right = Expression.Constant("F");
        Expression eqEx = Expression.Equal(paEx, right);
        Expression lE = Expression.Lambda<Func<ListTest, bool>>(eqEx, pe);

It should be a simple solution of 4 or 5 lines, but I can not find a simple solution.

Should I use MethodCallExpression or something on these lines?

Thank,

+3
2

- :

IEnumerable<ListTest> things = tryIt;

if (someBooleanLogic)
    things = things.Where(l => l.perSex == "F");
else
    things = things.Where(l => l.perName == "Tiger");

things = things.OrderBy(sex => sex.perName);

List<ListTest> filteredAndSorted = things.ToList();

Edit:

LINQ Dynamic Query Library, , (, ).

+1

. , hell.

0

Source: https://habr.com/ru/post/1771613/


All Articles