How can I sort a list based on a user's selections in ASP.NET MVC?

折月煮酒 提交于 2019-12-04 08:00:50

Have a look at http://tomasp.net/articles/dynamic-linq-queries.aspx for a tutorial on how to build Dynamic LinQ queries at runtime. This should be what you are looking for.

I solved this by chaining .OrderBy statements in a ForEach loop. An .OrderBy gets appended to my Linq query for each sort criterion selected by the user. By wrapping my list in an IQueryable, I'm able to see the Linq query as it is built.

IQueryable<CustomerMaster> query = customers.AsQueryable();

            // reverse the sort order (sorts are applied incrementally) 
            // We need the user's last
            // sort criteria to get applied first
            sortOrder.Reverse();

            foreach (var sortItem in sortOrder)
            {
                switch (sortItem)
                {
                    case "LName":
                        query = query.OrderBy(c => c.LName);
                        break;

                    case "State":
                        query = query.OrderBy(c => c.State);
                        break;

                    default:
                        query = query
                            .OrderBy(c => c.LName)
                            .ThenBy(c => c.State);
                        break;
                }
            }
            customers = query.ToList();
            // set the sortorder back to user's order
            sortOrder.Reverse();
        }

Resulting query:

query = {System.Collections.Generic
        .List`1[CustomerMaster]
        .OrderBy(c => c.LName)
        .OrderBy(c => c.State)}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!