You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在指定LINQ查询中实现基于日期字段的条件降序排序?

Yes, you can absolutely implement that sorting logic!

The trick is to use a ternary conditional operator inside your OrderByDescending clause to dynamically pick which date field to sort by based on whether DateUpdated is DateTime.MinValue. Here's how to adjust your code:

return database.Table<Announcement>()
    .Where(i => i.GroupId == groupId)
    .OrderByDescending(d => d.DateUpdated != DateTime.MinValue ? d.DateUpdated : d.DateCreated)
    .ToListAsync();

How this works:

  • For each announcement, we check if DateUpdated is not equal to DateTime.MinValue. If that's true, we use DateUpdated as the sort key.
  • If DateUpdated is DateTime.MinValue (meaning it was never updated), we fall back to using DateCreated instead.
  • This logic translates cleanly to SQL in most ORMs like Entity Framework Core, so the sorting happens on the database side—no need to fetch all records first and sort in memory.

Just swap out your original OrderByDescending line with the one above, and you'll get the behavior you want!

内容的提问来源于stack exchange,提问作者gooseman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:39:56