linq的多个orderby字符串列

时间:2015-03-13 17:03:44

标签: linq entity-framework

我的字符串包含用于使用linq进行排序的列名, 当字符串只包含一列时,它工作正常,但是当包含多列时,我不知道如何创建linq语句来对它们进行排序。

我的字符串是这样的:“ClassNo ASC,count DESC,floor ASC” 如果有一栏,我会尝试如下排序:

 switch (sort.Trim())
            {
                default:
                    result = result.OrderBy(u => u.ClassId);
                    break;
                case "ClassNo DESC":
                    result = result.OrderByDescending(u => u.ClassNo);
                    break;
                case "ClassNo ASC":
                    result = result.OrderBy(u => u.ClassNo);
                    break;
                case "count DESC":
                    result = result.OrderByDescending(u => u.count);
                    break;
                case "count ASC":
                    result = result.OrderBy(u => u.count);
                    break;
                case "floor DESC":
                    result = result.OrderByDescending(u => u.floor);
                    break;
                case "floor ASC":
                    result = result.OrderBy(u => u.floor);
                    break;
                case "ClassId DESC":
                    result = result.OrderByDescending(u => u.ClassId);
                    break;
            }

1 个答案:

答案 0 :(得分:1)

您可以这样做:

var ordered1 = result.OrderBy(x => x.count);
var ordered2 = ordered1.ThenBy(x => x.floor);
var ordered3 = ordered2.ThenByDescending(x => x.ClassId);

此处需要注意的是OrderBy()OrderByDescending()会返回IOrderedEnumerable<T>,然后您可以添加其他级别的订单。

所以在你的情况下,它会是这样的:

// convert to an IOrderedEnumerable<T>
var orderedResult = result.OrderBy(x => 1);

foreach (string part in sort.Split(','))
{
    switch (part.Trim())
    {
        case "ClassNo DESC":
            orderedResult = orderedResult.ThenByDescending(u => u.ClassNo);
            break;
        case "ClassNo ASC":
            orderedResult = orderedResult.ThenBy(u => u.ClassNo);
            break;
        case "count DESC":
            orderedResult = orderedResult.ThenByDescending(u => u.count);
            break;
        case "count ASC":
            orderedResult = orderedResult.ThenBy(u => u.count);
            break;
        case "floor DESC":
            orderedResult = orderedResult.ThenByDescending(u => u.floor);
            break;
        case "floor ASC":
            orderedResult = orderedResult.ThenBy(u => u.floor);
            break;
        case "ClassId DESC":
            orderedResult = orderedResult.ThenByDescending(u => u.ClassId);
            break;
        default:
            orderedResult = orderedResult.ThenBy(u => u.ClassId);
            break;
    }
}