C# LinQ 条件 OrderBy

标签: Asp.net Linq C#
发布时间: 2017/2/25 3:37:52
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

所以这是我的查询

 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 。 我想去 OrderBy 升序如果布尔值 true 和降序如果为 false。

如何实现这一目标呢?

解决方法 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);
}
官方微信
官方QQ群
31647020