如何用LINQ查询获取更新日期晚于指定日期的记录
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
DateTimeconstructor (most straightforward):var targetDate = new DateTime(2018, 3, 23); - Use
DateTime.ParseExactif 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

