I have one date filed in one object . I want to check if all dates are coming from same month [ Month can be anything ].
Below are the example for checking coming date are from current month .
@Model.Events.Where(d =>
System.Convert.ToDateTime(d.Eventdate).Month == System.Convert.ToInt32(month))
Well you could use something like:
bool allSameMonth = @Model.Events
.Select(x => x.EventDate.Month)
.Distinct()
.Count() < 2;
(I've taken the liberty of assuming you're going to change your Eventdate
model property from a string
property to a DateTime
property, and capitalize the D
. You really don't want to use strings all over the place. Convert to DateTime
as early as you can, and then convert back to strings only where you need to.)
This code doesn't care which month it is - only that there are fewer than 2 distinct months. (This means that "there are no events" counts as well. You need to consider how you want to handle that.)
See more on this question at Stackoverflow