动态KeyValuePair在foreach's顺序

本文关键字:顺序 KeyValuePair foreach 动态 | 更新日期: 2023-09-27 18:17:48

我试图复制SQL的ORDER BY。我从几个表中获取数据并将其添加到字典中。一切都很好,但我希望能够动态地排序数据。这意味着用户可能希望通过用户名,日期等来订购它。

string SortBy       = Request.QueryString["SortBy"];
string SortOrder    = Request.QueryString["SortOrder"];
foreach (KeyValuePair<Main_key, Main_data> entry in mainTable.OrderBy(key=> key.Value.username)
{
    ...
}

我想让这个部分是动态的:

key.Value.username

取决于用户输入

我知道这个答案,主要是这个片段,我试图使它工作,但因为我在KeyValuePair中使用一个结构,它不工作。

动态KeyValuePair在foreach's顺序

试试这个:

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
        }
    }
}