我有一个列表,我希望它按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();
答案 0 :(得分:5)
由于您使用的条件,您得到了数字排序的印象,正是a => a.DayOfWeek != 1
。它将需要所有非星期日(true
)并在星期日(false
)之后放置,这是OrderBy
对boolean
值进行排序的方式。
尝试:
.OrderByDescending(a => a.DayofWeek != 1).ThenBy(a => a.DayofWeek)
.OrderBy(a => a.DayofWeek == 1).ThenBy(a => a.DayofWeek)
答案 1 :(得分:0)
尝试:
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));