开发者

Is this an efficient way of doing a linq query with dynamic order by fields?

I have the following method to apply a sort to a list of objects (simplified it for the example):

private IEnumerable<Something> SetupOrderSort(IEnumerable<Something> input,
    SORT_TYPE sort)
{
    IOrderedEnumerable<Something> output = input.OrderBy(s => s.FieldA).
        ThenBy(s => s.FieldB);
    switch (sort)
    {
        case SORT_TYPE.FIELD1:
            output = output.ThenBy(s => s.Field1);
            break;
        case SORT_TYPE.FIELD2:
            output = output.ThenBy(s => s.Field2);
            break;
        case SORT_TYPE.UNDEFINED:
            break;
    }
    return output.ThenBy(s => s.FieldC).ThenBy(s => s.FieldD).
        AsEnumerable();
}

What I needs is to be able to insert a specific field in the midst of the orby clause. By default the ordering is: FIELDA, FIELDB, FIELDC, FIELDD.

When a sort field is specified though I need to insert the specified field between FIELDB and FIELDC in the sort order.

Currently there is only 2 possible fields to sort by but could be up to 8. Performance wise is this a good approach? Is there a more efficient way of doing this?

EDIT: I saw the following thread as well: Dynamic LINQ OrderB开发者_运维百科y on IEnumerable<T> but I thought it was overkill for what I needed. This is a snippet of code that executes a lot so I just want to make sure I am not doing something that could be easily done better that I am just missing.


Don't try and "optimize" stuff you haven't proved slow with a profiler.

It's highly unlikely that this will be slow enough to notice. I strongly suspect the overhead of actually sorting the list is higher than switching on one string.

The important question is: Is this code maintainable? Will you forget to add another case the next time you add a property to Something? If that will be a problem, consider using the MS Dynamic Query sample, from the VS 2008 C# samples page.

Otherwise, you're fine.


There's nothing inefficient about your method, but there is something unintuitive about it, which is that you can't sort by multiple columns - something that end users are almost sure to want to do.

I might hand-wave this concern away on the chance that both columns are unique, but the fact that you subsequently hard-code in another sort at the end leads me to believe that Field1 and Field2 are neither related nor unique, in which case you really should consider the possibility of having an arbitrary number of levels of sorting, perhaps by accepting an IEnumerable<SORT_TYPE> or params SORT_TYPE[] argument instead of a single SORT_TYPE.

Anyway, as far as performance goes, the OrderBy and ThenBy extensions have deferred execution, so each successive ThenBy in your code is probably no more than a few CPU instructions, it's just wrapping one function in another. It will be fine; the actual sorting will be far more expensive.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜