动态LINQ帮助排序问题

时间:2010-10-20 19:45:41

标签: linq linq-to-sql sorting dynamic predicate

我有一个简单的IEnumerable Order对象集合。我想编写一个泛型排序函数,它接受集合和一个与Order对象上的属性相对应的sortkey。我不想硬编码每个属性的排序指令。如何构建一个动态LINQ字符串,为我自动生成LINQ?这是我的SortOrders()函数的当前状态:

public IEnumerable<Order> SortOrders(IEnumerable<Order> orders, string sortKey)
        {
            // Sort order records
            try
            {
                IEnumerable<Order> sortedOrders = new List<Order>();

                // Extract sort key and direction from combined sortKey input
                string _sortKey = this.SortKey.Replace(" ASC", "").Replace(" DESC", "");
                bool sortASC = this.SortKey.EndsWith(" ASC");

                switch (_sortKey)
                {
                    case "CustomerID":
                        sortedOrders = (sortASC) ? orders.OrderBy(o => o.CustomerID) : orders.OrderByDescending(o => o.CustomerID);
                        break;
                    case "CustomerAddress":
                        sortedOrders = (sortASC) ? orders.OrderBy(o => o.CustomerAddress) : orders.OrderByDescending(o => o.CustomerAddress);
                        break;
                    case "CustomerCity":
                        sortedOrders = (sortASC) ? orders.OrderBy(o => o.CustomerCity) : orders.OrderByDescending(o => o.CustomerCity);
                        break;
                    default:
                        sortedOrders = orders;
                        break;
                }
                return sortedOrders;
            }
            catch
            {
                return orders; // return original orders list in the event of errors
            }
        }

我希望替换所有这样的案例部分:

case "CustomerID":
                        sortedOrders = (sortASC) ? orders.OrderBy(o => o.CustomerID) : orders.OrderByDescending(o => o.CustomerID);

使用如下的单个指令:

sortedOrders = (sortASC) ? orders.OrderBy(o => o.PropertyName) : orders.OrderByDescending(o => o.PropertyName);

2 个答案:

答案 0 :(得分:1)

您可以将要排序的表达式作为Lamba传递(这是简化/伪代码)

SortOrders(IEnumerable<Order> orders, Func<Order, string> func)
{
    sortedOrders = orders.OrderBy(func) 
    ....                
}


// call:
SortOrders(orders,  o => o.CustomerID);

答案 1 :(得分:1)

您可以使用Dynamic LINQ,也不需要扩展方法。只需在DynamicQueryable类中使用扩展名,并将键和方向指定为字符串。

var sorted = orders.OrderBy( "CustomerID desc" );