I have a List which contains dates from June 1, 2009 to June 1, 2014. How would I query it in C# LINQ to select only the first date of each month?
+7
A:
The simplest way I think is to filter by the Day property of your dates:
var firstDays = dates.Where(d=> d.Day == 1);
CMS
2009-10-01 23:18:38
The wording of the question is horrible. This is a great solution if you want the 1st of every month that appears in the list (e.g. 1st Jan, 1st Feb etc), but it won't work if you want the first date that appears in the list for each month (e.g. 2nd Jan if the 1st Jan is not in the list, etc)
Kirk Broadhurst
2009-10-02 01:26:52
+5
A:
Your question is slightly ambiguous. If you want the first item appearing in the list in each month, you can use:
var result = list.GroupBy(x => new { x.Year, x.Month })
.Select(x => x.Min());
Mehrdad Afshari
2009-10-01 23:19:27
+2
A:
Like this:
dates.Where(d => d.Day == 1);
Or, using query comprehension,
from d in dates where d.Day == 1 select d;
SLaks
2009-10-01 23:19:31
+2
A:
Try the following
public static bool IsFirstDayOfMonth(this DateTime t) {
var other = new DateTime(t.Year,t.Month,1);
return other == t.Date;
}
var allDates = GetTheDates();
var filter = allDates.Where(x => x.IsFirstDayOfMonth());
JaredPar
2009-10-01 23:20:59