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

如何编写带Where子句的LINQ查询,筛选9点至17点的Timestamp类型记录

Filter LINQ Query for Timestamps Between 9 AM and 5 PM (India Standard Time)

Got it, let's tweak your existing LINQ query to add the time range filter you need. The core idea is converting the UTC timestamp to India Standard Time first, then checking if it falls within your desired 9 AM to 5 PM window.

Here's the revised code with the time filter included, plus a small optimization to avoid repeating timezone conversions:

var items = Pirs
    // First filter out unwanted dataframe entries
    .Where(a => !a.dataFrame.EndsWith("AAAAAAAAAAA="))
    // Convert UTC timestamp to India Standard Time once (cuts down on redundant calculations)
    .Select(a => new 
    {
        OriginalItem = a,
        IstDateTime = TimeZoneInfo.ConvertTimeFromUtc(
            Convert.ToDateTime(a.timestamp), 
            TimeZoneInfo.FindSystemTimeZoneById("India Standard Time")
        )
    })
    // Apply date range + new time range filters
    .Where(x => 
        // Your existing date range checks
        (fromDate == null || fromDate.Value.Date <= x.IstDateTime.Date) &&
        (toDate == null || toDate.Value.Date >= x.IstDateTime.Date) &&
        // Filter for 9 AM to 5 PM (inclusive of both endpoints)
        x.IstDateTime.TimeOfDay >= TimeSpan.FromHours(9) && 
        x.IstDateTime.TimeOfDay <= TimeSpan.FromHours(17)
    })
    // Retrieve the original item
    .Select(x => x.OriginalItem)
    // Your existing grouping, selection and ordering logic
    .GroupBy(a => a.dataFrame.Substring(a.dataFrame.Length - 12))
    .Select(g => g.First())
    .OrderBy(a => a.timestamp);

A few key details about the time filter:

  • I used TimeOfDay instead of just checking the hour for precision. This ensures we include exactly 9:00 AM up to and including 5:00 PM (and exclude anything after 5:00 PM, like 5:01 PM).
  • If you only care about the hour (and don't mind including 5:00 PM to 5:59 PM), you can simplify the time check to:
    x.IstDateTime.Hour >= 9 && x.IstDateTime.Hour <= 17
    
  • The intermediate Select step is optional but recommended—it converts the timezone once per item instead of multiple times in the Where clause, making the query more efficient.

Quick checks to keep in mind:

  • Ensure a.timestamp can reliably be converted to a DateTime with Convert.ToDateTime—if there's any chance of invalid values, add a DateTime.TryParse check to avoid runtime exceptions.
  • If you're using an ORM like Entity Framework, verify that your query provider supports TimeZoneInfo methods. If not, you might need to handle timezone conversion at the database level (e.g., using SQL Server's AT TIME ZONE function).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:57:12