本文介绍了如何在规范中生成动态数量的ThenBy子句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个Spec Evaluator,它必须考虑多个可能的OrderBy,如下例所示:

I'm building a Spec Evaluator which must consider multiple possible OrderBy, as in the next example:

if (spec.Order != null)
{
    var count = spec.Order.Count;

    if (count == 1)
    {
        query = query.OrderBy(spec.Order[0]);
    }
    else if (count == 2)
    {
        query = query.OrderBy(spec.Order[0])
            .ThenBy(spec.Order[1]);
    }
    else if (count == 3)
    {
        query = query.OrderBy(spec.Order[0])
            .ThenBy(spec.Order[1])
            .ThenBy(spec.Order[2]);
    }
    // And so on...
}

QueryIQueryablespec.Order是子句列表:List<Expression<Func<T, object>>>.

我知道我可以将OrderBy与所有作为字符串传递的子句一起使用.而且我想我可以将所有Order子句投影到一个用逗号分隔的新字符串中.但是该解决方案似乎并不干净.

I know that I can use an OrderBy with all the clauses passed as string. And I guess I can just project all the Order clauses to a new string comma-separated. But that solution doesn't seem clean.

是否还有其他方法可以为Order列表中大于1的每个项目动态生成一个新的ThenBy?

Is there any other way to dynamically generate one new ThenBy for every item of the Order list, above 1?

推荐答案

您可以使用for循环.基本上遍历所有Order值,对于第一个使用OrderBy,对于后续项使用ThenBy.由于您已经说过您正在使用IQueryable,因此我已对其进行了修改,以使用临时的IOrderedQueryable<T>变量.

You could use a for loop. Basically loop through all of the Order values, use OrderBy for the first one, and ThenBy for subsequent items. Since you've said that you're using IQueryable, I've modified this to use a temporary IOrderedQueryable<T> variable.

if (spec.Order != null)
{
    var count = spec.Order.Count;

    IOrderedQueryable<T> orderedQuery = null;
    for (int i = 0; i < count; ++i)
    {
        if (i == 0)
        {
            orderedQuery = query.OrderBy(spec.Order[i]);
        }
        else
        {
            orderedQuery = orderedQuery.ThenBy(spec.Order[i]);
        }
    }
    query = orderedQuery ?? query;
}

您也可以这样处理,尽管我不确定这两种方法之间的性能有何不同,

You could also approach it like this, although I'm not sure how the performance differs between the two methods, if it does at all:

if (spec.Order != null)
{
    var count = spec.Order.Count;

    for (int i = 0; i < count; ++i)
    {
        if (query is IOrderedQueryable<T> orderedQuery)
        {
            query = orderedQuery.ThenBy(spec.Order[i]);
        }
        else
        {
            query = query.OrderBy(spec.Order[i]);
        }
    }
}

这篇关于如何在规范中生成动态数量的ThenBy子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 22:40