繁体   English   中英

C#中的通用DateTime列表比较

[英]Generic DateTime List Comparison in C#

我有一个通用的DateTime列表

List<DateTime> **PreviousDates** = //Some List of Dates

现在,我想获取PreviousDate列表中其Month和Year等于GivenDate的Month&Year的所有日期。 不管是什么日期和时间

我尝试使用List.Contains()方法,但是它检查日期的所有部分,我只想检查Month&Year。

帮我!

感谢Pradeep

您需要使用Where方法。 它将过滤列表,您可以将“年”和“月”与当前日期进行比较。

DateTime currentDate = DateTime.Now;
var filteredDates = previousDates.Where(
    d => d.Year == currentDate.Year && d.Month == currentDate.Month);

您可以使用LINQ返回IEnumerable

PreviousDates.Where(d => d.Month == month && d.Year == year);

您可以尝试类似

DateTime criteria = DateTime.Today;
List<DateTime> filtered = previousDates.Where(dt => dt.Month == criteria.Month && dt.Year == criteria.Year).ToList();
previousDates.Where(d => d.Month == refDate.Month && d.Year == refDate.Year);

您可以为间隔的开始和结束创建DateTime值:

DateTime start = new DateTime(GivenDate.Year, GivenDate.Month, 1);
DateTime end = start.AddMonths(1);

现在,您可以轻松选择时间间隔内的项目:

List<DateTime> inside =
  PreviousDates
  .Where(d => d >= start && d < end)
  .ToList();

(你当然可以比较GivenDate.YearGivenDate.Monthd.Yeard.MonthWhere ,但这是一个更复杂,效率较低的状态。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM