tags:

views:

418

answers:

1

I'll preface this with saying I'm day 8 into life as a C# developer.

For a number of DomainModels in the project I am working on, I need the ability to filter all records in a table given what a user submits in a review/search form.

Currently the 2 cent short tour is:

Form submits to FooController/review.

Review then grabs all key/value pairs from Params['filter'] into a dictionary and passes that to a helper class call FooFinder.ByProperties which looks very similar to:

public IQueryable<WorkPlan> ByProperties( IDictionary<string, string> properties)
    {            

        var result = ForSite(Convert.ToInt64(properties.DefaultVal("SiteId", "0")));

        v);

        if(properties.ContainsKeyAndIsNotNullOrEmpty("WorkPlan.Key"))
        {
            var tempVal = Convert.ToInt64(properties["WorkPlan.Key"]);
            result = result.Where(r => r.Id == tempVal);
        }
        // Multiple of these conditional checks follows
       return result;

}

I'd like to cut down on repetative code as much as possible and tried something like

result = ByProperty(properties, "WorkPlan.key", typeof (Int64), r, v => r.id == v);

But thats obviously not going to work for a lot of reasons... still the idea of what I'm trying to accomplish is there. I'd really like to simplify the code down and speed up the process of filtering by using some sort of dynamic helper/utility.

Other idea's I tried was using Reflection and that kid of works for straight comparisons, but then how to check for things like a CreatedDatime property where I want all records greater then " r => CreatedDatetime > CreatedFrom".

If none of this makes sense please comment and I'll try to clear up any issues.

+1  A: 

What you are asking can be automated, but it is quite a lot of work, and requires a knowledge of the Expression API. Which is quite an advanced topic.

I would probably keep the code "as is"... dry is fine, but "don't break working code" is another adage worth knowing...

Alternatively, you might want to look at the Dynamic LINQ Library - this might help you automate things. But to be honest, the existing code isn't that ugly...

Marc Gravell
Thats the conclusion I reached when I found the Dynamic Linq Library on my own. Its pretty cool but I can't afford to implement right now.
David