views:

48

answers:

2

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,

+1  A: 

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).

shaunmartin
Trying to use the MethodCallExpression in order to keep the query dynamic. I will want to change the parameter expression to different properties of the object. For instance having the query return the collection ordered by perName.
Glen Wilkinson
Ok. I'm not *entirely* sure I understand what your goal is, but I've added another resource to my answer - the LINQ Dynamic Query Library. You may already be aware of it, but if not, it may be of use to you - it's pretty powerful.
shaunmartin
LINQ Dynamic Query Library is the way to go...
codekaizen
A: 

I found the most elegant solution on this post. It allowed my to construct a very flexible and clear solution without getting into parameter hell.

Glen Wilkinson