在LINQ OrderBY中排除一个值

本文关键字:一个 LINQ OrderBY 排除 | 更新日期: 2023-09-27 18:21:18

我有一个列表,我希望它按DayOfWeek排序,除了DayOfWeek=1的情况,它应该在列表的末尾。我在OrderBy和ThenBy上尝试了一些变体,但它似乎继续按数字顺序排序。

我相信这很简单,我不想更改Day=1的值,这是的原始解决方案

var dayOfWeeksHolder = Enumerable.Range(1, 7);   
var defaultTime = DateTime.Today.TimeOfDay;
var psList = _pickingScheduleIO.GetDayScheduleList(branchNo);
var psListByType = psList.Where(p => p.PickingSesstionTypeId == pickingSessionTypeId).ToList();
var fullList = (from d in dayOfWeeksHolder
                join s in psListByType on d equals s.DayOfWeek into grp
                from ds in grp.DefaultIfEmpty()
                // where (ds == null || ds.PickingSesstionTypeId == pickingSessionTypeId)
                select new DayScheduleVM
                {
                    PickingScheduleId = ds == null ? 0 : ds.PickingSessionScheduleId,
                    DayOfWeek = d, //d == 1 ? d + 7 : d, //in sql sunday is 1, we need to make it to 8 so it will be sorted to last
                    StartTime = ds == null ? defaultTime : ds.StartTime,
                    EndTime = ds == null ? defaultTime : ds.EndTime,
                    PickingSessionTypeId = pickingSessionTypeId
                }).OrderBy(a => a.DayOfWeek !=1).ThenBy(a => a.DayOfWeek);
return fullList.ToList();

在LINQ OrderBY中排除一个值

由于您使用的条件,确切地说是a => a.DayOfWeek != 1,您得到了数字排序的印象。它将占用所有非星期日(true),并将它们放在星期日之后(false),这就是OrderByboolean值进行排序的方式。

尝试其中一种:

  • .OrderByDescending(a => a.DayofWeek != 1).ThenBy(a => a.DayofWeek)
  • .OrderBy(a => a.DayofWeek == 1).ThenBy(a => a.DayofWeek)

尝试:

var fullList = (from d in dayOfWeeksHolder
                        join s in psListByType on d equals s.DayOfWeek into grp
                        from ds in grp.DefaultIfEmpty()
          //              where (ds == null || ds.PickingSesstionTypeId == pickingSessionTypeId)
                        select new DayScheduleVM
                        {
                            PickingScheduleId = ds == null ? 0 : ds.PickingSessionScheduleId,
                            DayOfWeek = d,//d == 1 ? d + 7 : d, //in sql sunday is 1, we need to make it to 8 so it will be sorted to last
                            StartTime = ds == null ? defaultTime : ds.StartTime,
                            EndTime = ds == null ? defaultTime : ds.EndTime,
                            PickingSessionTypeId = pickingSessionTypeId
                        });
return fullList.SkipWhile(a => a.DayOfWeek == 1).OrderBy(a => a.DayOfWeek).Concat(fullList.TakeWhile(a => a.DayOfWeek == 1));