Dynamic LINQ with Data Objects [duplicate]
So I have been searching for a simple example to hopefully a simple problem.
I have a simple object a List of ListTest (List)
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 have loaded 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 it dynamically, just in case I want to change my where to "perName".
I am able to create the Lambda Expression your Expressions, but I can't figure out how to take it across the goal line and actually assign it to 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);
This should be a simple 4 or 5 line solution, but I can't find an easily decipherable solution example.
Should I use a MethodCallExpression or something down those lines?
Thanks,
You can try something like this:
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:
Or, there's also the popular LINQ Dynamic Query Library, where you can form your query pretty much however you want (dynamically, of course).
精彩评论