I have a Generic DateTime List
List<DateTime> **PreviousDates** = //Some List of Dates
Now i want to Get all the Dates in the PreviousDates List whose Month and Year equals the GivenDate's Month & Year. no matter what the Day & Time are...
I Tried using List.Contains() method, but it checks all Parts of the Date, i want to check only Month&Year..
Help Me!
Thanks Pradeep
You need to use the Where method. It will filter the list, and you can compare the Year and Month to the current date.
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);
You can try something like
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);
You can create DateTime
values for the start and end of the interval:
DateTime start = new DateTime(GivenDate.Year, GivenDate.Month, 1);
DateTime end = start.AddMonths(1);
Now you can easily select the items that is inside the interval:
List<DateTime> inside =
PreviousDates
.Where(d => d >= start && d < end)
.ToList();
(You could of course compare the GivenDate.Year
and GivenDate.Month
values to d.Year
and d.Month
in the Where
, but that's a more complex and less efficient condition.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.