📅  最后修改于: 2023-12-03 15:30:07.694000             🧑  作者: Mango
LINQ (Language Integrated Query) is a powerful feature in C# that allows developers to query data from different data sources (e.g., SQL Server, XML, collection objects) using a unified syntax. When working with datetime values in LINQ, it's often necessary to filter the data based on a range of dates. In this article, we will explore how to use LINQ to filter data based on datetime between two specific dates.
The DateTime
struct in C# has a built-in method called Between
that can be used to check whether a datetime value falls between two specific dates. The method takes three parameters: the datetime value to check, the start date, and the end date. Here's the method signature:
public static bool Between(this DateTime dt, DateTime start, DateTime end)
Suppose we have a list of orders with order dates, and we want to retrieve all orders that were placed between January 1, 2020, and December 31, 2020:
List<Order> orders = GetOrders();
DateTime start = new DateTime(2020, 1, 1);
DateTime end = new DateTime(2020, 12, 31);
var filteredOrders = orders.Where(o => o.OrderDate.Between(start, end));
The Where
method takes a lambda expression that defines the filter criteria. In this case, we are filtering the orders based on their OrderDate
property by calling the Between
method with the start
and end
dates.
Using the Between
operator makes it easy to filter datetimes within a specific range in LINQ. Keep in mind that DateTime
values are precise to the nearest tick (100 nanoseconds), so when specifying the start
and end
dates, make sure to provide a time value (e.g., midnight) to ensure that all datetime values within the range are included in the result set.