1

I'm trying to replicate SQL's ORDER BY. I'm fetching data from several tables and adding it to a dictionary. Everything is working fine, but I would like to be able to order the data dynamically. Meaning the user might want to order it by username, date, etc.

string SortBy       = Request.QueryString["SortBy"];
string SortOrder    = Request.QueryString["SortOrder"];

foreach (KeyValuePair<Main_key, Main_data> entry in mainTable.OrderBy(key=> key.Value.username)
{
    ...
}

I want to make this part dynamic:

key.Value.username

Depending on the user input.

I'm aware of this answer and mainly of this snippet that I'm trying to make it work, but because i'm using a structure in the KeyValuePair, it's not working.

Community
  • 1
  • 1
Cornwell
  • 3,084
  • 5
  • 41
  • 73
  • 1
    In your Main_data class, just expose a method that takes the SortBy parameter and returns the appropriate value. E.g. GetOrderBy(string sortBy) { switch (sortBy) { case "username" : return username; case "address": return address; } } – Jon Aug 13 '14 at 18:51
  • 1
    Then mainTable.OrderBy(key=> key.Value.GetOrderBy(SortBy)); – Jon Aug 13 '14 at 18:51
  • @Mangist Interesting. I guess that could work in smaller tables. Anything I could about the sort order? – Cornwell Aug 13 '14 at 18:56

1 Answers1

2

Try this:

public class Main_data
{
    public string username { get; set; }
    public string name { get; set; }
    public string address { get; set; }

    public string GetSortBy(string sortBy)
    {
        switch (sortBy)
        {
            case "username": return username;
            case "name": return name;
            case "address": return address;
            default:
                throw new NotSupportedException(
                    String.Format("Cannot sort on {0}", sortBy));
        }
    }
}

public class DataBinder
{
    public void BindData()
    {
        string sortBy       = Request.QueryString["SortBy"];
        string sortOrder    = Request.QueryString["SortOrder"];

        IEnumerable<KeyValuePair<Main_key, Main_data>> records = null;
        if (sortOrder = "Asc")
        {
            records = mainTable.OrderBy(key=> key.Value.GetSortBy(SortBy);
        }
        else if (sortOrder == "Desc")
        {
            records = mainTable.OrderByDescending(key=> key.Value.GetSortBy(SortBy);
        }
        else
        {
            throw new NotSupportedException("Unknown sortOrder");
        }

        foreach (KeyValuePair<Main_key, Main_data> entry in records)
        {
            // TODO: Do something with the records
        }
    }
}
Jon
  • 3,080
  • 1
  • 13
  • 26