如何编写动态LINQ查询并使用Orderby [Sort Direction]

时间:2013-09-03 20:30:49

标签: c# linq entity-framework-4

我想写一个类似于这个SQL查询的LINQ查询:

从SomeTable选择ID,标题,说明,日期

然后动态添加' OrderBy' ' Ascending / Descending'

我需要在gridview上添加排序功能,其数据源是此linq查询。

1 个答案:

答案 0 :(得分:2)

您可以编写自己的SortBy扩展方法,该方法需要SortDirection

public enum SortDirection { Ascending, Descending }

public static class Extensions
{
    public static IEnumerable<TSource> SortBy<TSource, TKey>(
        this IEnumerable<TSource> source,
        SortDirection sortDirection,
        Func<TSource, TKey> keySelector)
    {
        switch (sortDirection)
        {
            case SortDirection.Ascending:
                return source.OrderBy(keySelector);
            case SortDirection.Descending:
                return source.OrderByDescending(keySelector);
            default:
                throw new ArgumentOutOfRangeException();
        }
}

<强>用法

var sortDirection = Sort.Descending; // this could be set dynamically at runtime
var sorted = new[] { 1, 2, 3 }.SortBy(SortDirection.Descending, x => x);