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

如何用LINQ查询获取更新日期晚于指定日期的记录

Fixing the LINQ Query to Filter Records by Updated Date

Hey Krishna, let's get your LINQ query working correctly to fetch records where updatedate is later than March 23, 2018. Here are the key issues with your current code and how to fix them:

1. The Date Comparison Bug

Your current date check x.updatedate > 22/03/2018 won't work as expected. In C#, 22/03/2018 is treated as integer division (22 divided by 3 divided by 2018), resulting in 0—not a valid DateTime value. You need to explicitly create a DateTime object for your target date.

You have two reliable options here:

  • Use the DateTime constructor (most straightforward):
    var targetDate = new DateTime(2018, 3, 23);
    
  • Use DateTime.ParseExact if you need to enforce a specific date format (avoids culture-related parsing issues):
    var targetDate = DateTime.ParseExact("23/03/2018", "dd/MM/yyyy", CultureInfo.InvariantCulture);
    

2. Optimize LINQ Execution Order

Your current code first sorts all records, takes the top 100, then filters. This is inefficient because you're sorting more data than needed, and you might miss valid records that fall outside the first 100 sorted entries. Instead, filter first, then sort, then take the top 100—this reduces the dataset early on for better performance.

Full Corrected Code

Here's the revised version of your code with these fixes:

// Deserialize the response as before
List<MDetails> Pirs = Newtonsoft.Json.JsonConvert.DeserializeObject<List<MDetails>>(responseString);

// Define your target date
var targetDate = new DateTime(2018, 3, 23);

// Filter first, then sort, then take top 100
Pirs = Pirs
    .Where(x => x.updatedate > targetDate)
    .OrderByDescending(x => x.timestamp)
    .Take(100)
    .ToList();

Bonus: Handling Nullable Dates

If your updatedate property might be null (i.e., defined as public DateTime? updatedate { get; set; }), adjust the filter to check for null first:

.Where(x => x.updatedate.HasValue && x.updatedate.Value > targetDate)

That should give you exactly the records you're looking for!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:18:35