How to Sort a List Generically

I am using an Html.Grid of a set of objects which are being pulled from a database (via LINQ to SQL). Here is the Grid code (I have changed the data to something contrived). The page is strongly-typed to People.

<%=Html.Grid<People>(Model)    
// Display chose solution information.
    .Columns(column =>
        {
            column.For(person => person.Name);
            column.For(person => person.Address.City);
        }
    )
%>

Within the database, I would have a People table and an Address table linked by a foreign key. (Again, this is contrived - just trying to describe the problem.)

I want to allow the user to generically sort the columns. The previous developer had hard-coded in the sorting within the controller, like so...

//
// GET: Results/Grid
public ActionResult Grid(int id, GridSortOptions sort)
{
    if (sort == null)
    {
        sort = new GridSortOptions();
    }

    Solution solution = repository.GetSolution(id);
    List<People> people = solution.People.ToList();
    if (!string.IsNullOrEmpty(sort.Column))
    {
        people = solution.People.ToList().OrderBy(sort.Column, sort.Direction).ToList();
    }

    return PartialView("Grid", people);
}

This works great when the object I am sorting is people (if I click on the person.Name column to sort it ascending or descending). However, when I want to sort the address column, I get an exception because People does not contain a City...Address does.

My question is...is there a way to do this sort generically without knowing what the type is ahead of time? Thanks.

Answers


How about a javascript table sorter? Of course that won't work if your list is big enough to require paging.


I posted a similar question a little while back. The answers I got on that post might help you get on your way:

Looking for a better way to sort my List

Basically the answers suggest holding map of Func<> (or similar) and calling the appropriate one in the code block.


Need Your Help

Single Table Inheritance & ActiveRecord Associations

ruby-on-rails inheritance activerecord abstract-class single-table-inheritance

I'm attempting to have a parent model that other models inherit from, and a secondary class that has associations with the children from the first model. Here's what I have so far...

Custom directives not active in nested views when using ui-router

javascript angularjs angular-ui-router

I was working on an angular app (phonegap+ionic+angular), I had written a custom directive which registered an event listener for that element (which would activate iScroll for that element on load