如何在C#中汇总订单依据?

时间:2019-01-10 23:02:23

标签: c# entity-framework aggregate

因此,我有一个类似下面的函数,该函数接收对象列表并将其包含在我的查询字符串中。效果很好。

$('#sort-brand').find('option[text="All"]').attr('selected', 'selected');

但是我想做的就是也要聚合OrderBy。这是我遇到问题的地方。我的问题是,必须在同一行上使用 OrderBy ,然后使用 ThenBy 。我试过使用for循环第一项使用顺序,然后再使用thenby。我正在运行的问题是,为了激活thenby,订单必须在同一对象行上进行处理。

query = includeExpressions.Aggregate(query, (current, include) => current.Include(include));

我做不到

query.OrderBy(orderBy).ThenBy

我想像

var usedOrderBy = true;
        foreach (var orderBy in orderBys)
        {
            if (usedOrderBy)
            {
                query = query.OrderBy(orderBy);

                usedOrderBy = true;
            }
            else
            {
                query = query.ThenBy(orderBy); // <-- Can not locate thenby
            }
        }

any ides.

3 个答案:

答案 0 :(得分:2)

问题出在query变量的类型中。 ThenBy是可以应用于System.Linq.IOrderedEnumerable<TSource>System.Linq.IOrderedQueryable<TSource>的扩展方法,因此您不能仅仅这样做

IEnumerable<Point> points = GetPoints();
points = points.OrderBy(p => p.X);
points = points.ThenBy(p => p.Y);

您应该为预排序结果提供一个额外的变量,以解决您的情况,如以下示例所示:

IEnumerable<Point> points = GetPoints();
var orderedPoints = points.OrderBy(p => p.X);
orderedPoints = orderedPoints.ThenBy(p => p.Y);

答案 1 :(得分:0)

检查

   var orderByList = new List<Expression<Func<TEntity, object>>>();
            Expression<Func<TEntity,object>> orderBy1 = x => x.Id;
            Expression<Func<TEntity, object>> orderBy2 = x => x.ToString();
            Expression<Func<TEntity, object>> orderBy3 = x => x.Id;
            orderByList.Add(orderBy1);
            orderByList.Add(orderBy2);
            orderByList.Add(orderBy3);

            var resultOrderedQueryable = orderByList.Aggregate<Expression<Func<TEntity, object>>, IOrderedQueryable<TEntity>>(null, (current, orderBy) => current != null ? current.ThenBy(orderBy) : query.OrderBy(orderBy));

答案 2 :(得分:0)

如果查询的初始种子为OrderBy,则您的查询将起作用。然后,您可以链接ThenBy's。如前所述,ThenBy在附加IOrderedEnumerable子句之前首先需要IOrderedQueryable(或ThenBy):

您的代码如下所示:

IOrderedQueryable<T> orderedQuery = null;
for(int temp = 0; temp < orderBys.Count; temp++)
{
    if(temp == 0)
        orderedQuery = query.OrderBy(orderBys[temp]);

    else orderedQuery = orderedQuery.ThenBy(orderBys[temp]);  
}
query = orderedQuery ?? query;

参考:How to generate a dynamic number of ThenBy clauses in a Specification