[英]Exclude one value in LINQ OrderBY
I have a list, and I would like it to be sorted by DayOfWeek, except for the case where DayOfWeek=1, which should go at the end of the list. 我有一个列表,我希望按DayOfWeek进行排序,但DayOfWeek = 1的情况除外,该列表应位于列表的末尾。 I have tried a few variations on OrderBy and ThenBy, but it seems to continue to sort in numerical order.
我在OrderBy和ThenBy上尝试了一些变体,但它似乎继续按数字顺序排序。
I am sure this is very simple, and I don't want to change the value of the Day=1, which was the original solution 我确信这很简单,并且我不想更改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();
You got an impression of numerical sort because of condition you used, precisely a => a.DayOfWeek != 1
. 由于使用的条件,您对数字排序印象深刻,恰好
a => a.DayOfWeek != 1
。 It will take all non-Sundays ( true
) and place them after Sundays ( false
), which is how OrderBy
sorts boolean
values. 它将占用所有非星期日(
true
)并将它们放置在星期日( false
)之后,这是OrderBy
boolean
值进行排序的方式。
Try either: 尝试以下任一方法:
.OrderByDescending(a => a.DayofWeek != 1).ThenBy(a => a.DayofWeek)
.OrderBy(a => a.DayofWeek == 1).ThenBy(a => a.DayofWeek)
Try: 尝试:
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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.