C#LinQ条件订单

时间:2017-01-10 05:39:45

标签: c# asp.net linq

所以这是我的查询

 var results = tcs.Skip(searchModel.PageSize * (searchModel.Page - 1))
                .Take(searchModel.PageSize)
                .AsEnumerable()
                .Select(x => new
                {
                    trackId = x.TrackId,
                    trackName = x.TrackName,
                    category = _weCategoryService.FindAll().Where(y => y.WorkExperience_Track.TrackId == x.TrackId)
                        .Select(y => new {
                            categoryId = y.CategoryId,
                            categoryName = y.CategoryName,
                            skill = _skillsService.FindAll().Where(z => z.CategoryId == y.CategoryId)
                                .Select(z => new {
                                    skillId = z.SkillId,
                                    skillName = z.SkillName
                                }).OrderBy(z => z.skillName).ToList()
                        }).OrderBy(y => y.categoryName).ToList()
                }).OrderBy(x => x.trackName).ToList();

然后我的模型具有SortTrackSortCategorySortSkills的布尔值。 如果布尔值为true,我想要OrderBy Ascending,如果为false则为Descending。

如何实现?

3 个答案:

答案 0 :(得分:1)

Linq语句是可组合的,因此您可以在调用tolist之前向查询添加适当的orderby。

var query = list.Where(...)
if (condition)
    query = query.OrderBy(...)
else
    query = query.OrderByDescending(...)

return query.ToList();

答案 1 :(得分:1)

在lambda中可以这样做:

var results = tcs.Skip(searchModel.PageSize * (searchModel.Page - 1))
                    .Take(searchModel.PageSize)
                    .AsEnumerable()
                    .Select(x => new
                    {
                        trackId = x.TrackId,
                        trackName = x.TrackName,
                        category = _weCategoryService.FindAll().Where(y => y.WorkExperience_Track.TrackId == x.TrackId)
                            .Select(y => new {
                                categoryId = y.CategoryId,
                                categoryName = y.CategoryName,
                                skill = _skillsService.FindAll().Where(z => z.CategoryId == y.CategoryId)
                                    .Select(z => new {
                                        skillId = z.SkillId,
                                        skillName = z.SkillName
                                    }).OrderBy(z => SortSkills ? z.skillName : "").OrderByDescending(z => !SortSkills ? z.skillName : "").ToList()
                            }).OrderBy(y => SortCategory ? y.categoryName : "").OrderByDescending(y => !SortCategory ? y.categoryName : "").ToList()
                    }).OrderBy(x => SortTrack ? x.trackName : "").OrderByDescending(x => !SortTrack ? x.trackName : "").ToList();

否则你需要使用这样的表达式:

var x = widgets.Where(w => w.Name.Contains("xyz"));
if (flag) {
  x = x.OrderBy(w => w.property);
} else {
  x = x.OrderByDescending(w => w.property);
}

答案 2 :(得分:1)

以下是LINQ精神中的其他一些选项。 EF无法将它们转换为SQL,因此您需要在内存中运行这些内容(后AsEnumerable / ToArray / ToList),但看起来它不会成为问题。

以此为例:

var numbers = new int[] { 5, 1, 2, 3, 44 };

选项1

public static class EnumerableExtensions
{
    public static IOrderedEnumerable<T> OrderByAdaptive<T, TKey>(
        this IEnumerable<T> enumr, 
        Func<T, TKey> selector, 
        bool ascending
    )
    {
        return ascending
            ? enumr.OrderBy(selector)
            : enumr.OrderByDescending(selector);
    }

    public static IOrderedEnumerable<T> OrderByAdaptive<T, TKey>(
        this IEnumerable<T> enumr, 
        Func<T, TKey> selector, 
        IComparer<TKey> comparer, 
        bool ascending
    )
    {
        return ascending
            ? enumr.OrderBy(selector, comparer)
            : enumr.OrderByDescending(selector, comparer);
    }
}

用法

var asc = true; // or false
var sorted = numbers.OrderByAdaptive(x => x, asc);

选项2

public class LambdaComparer<T> : IComparer<T>
{
    private Func<T, T, int> _cmp;

    public LambdaComparer(Func<T, T, int> cmp)
    {
        _cmp = cmp;
    }

    public int Compare(T x, T y)
    {
        return _cmp(x, y);
    }
}

用法

var ascComparer = new LambdaComparer<int>((x, y) => { 
    if (x > y) return 1; 
    else if (x < y) return -1; 
    else return 0; 
});

var descComparer = new LambdaComparer<int>((x, y) => { 
    if (x > y) return -1; // Note the sign change
    else if (x < y) return 1; // Note the sign change
    else return 0; 
});

var asc = true; // or false

var sorted = numbers.OrderBy(x => x, asc ? ascComparer : descComparer);

选项3

public class ReverseComparer<T> : IComparer<T> where T : IComparable<T>
{
    private IComparer<T> _nonReversed;

    public ReverseComparer()
    {
        _nonReversed = Comparer<T>.Default;
    }

    public ReverseComparer(IComparer<T> nonReversed)
    {
        _nonReversed = nonReversed;
    }

    public int Compare(T obj1, T obj2)
    {
        return -1 * _nonReversed.Compare(obj1, obj2);
    }
}

用法

var ascComparer = Comparer<int>.Default;
var descComparer = new ReverseComparer<int>(); // or new ReverseComparer<int>(ascComparer);

var asc = true; // or false

var sorted = numbers.OrderBy(x => x, asc ? ascComparer : descComparer);

从生产方面来说,我可能会创建一个SortDirection枚举,其中包含AscendingDescending值,而不是名为asc的bool,但我很傻这一点。