Reputation: 19
How to loop every month's first date.
public struct stat{
public DateTime date;
}
I have a List<stat>
that have a date property. I want to get the lowest and newest one by sorting. the first element is older and last is newer one.
I can easily got the first and second by order by.
What I want is get 1st date of every month in the between of both first (oldest ) and newest.
string ret = "";
List<DateTime> dates = new List<DateTime>();
int breaker = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);
stats = stats.OrderBy(x => x.Date).ToList();
DateTime old = stats.First().Date;
DateTime @new = stats.Last().Date;
int diffdays = @new.Subtract(old).Days;
DateTime loopd = DateTime.Now;
for (int i = 0; i < diffdays; i = i + breaker)
{
loopd = loopd.AddDays(-breaker);
dates.Add(loopd);
if (loopd < old)
Console.WriteLine("date" + old);
}
for (int j = 0; j < dates.Count; j++)
{
if (j == 0)
{
DateTime ld= dates[0];
stats.SelectMany(x => x.Date < @new && x.Date > dates[j]);
}
}
Upvotes: 0
Views: 8604
Reputation: 460058
I want to get the lowest and newest one by sorting
I assume lowest means oldest.
stat oldest = stats.OrderBy(s => s.date).FirstOrDefault();
stat newest = stats.OrderByDescending(s => s.date).FirstOrDefault();
you could also use
stats.OrderBy(s => s.date).LastOrDefault();
to get the newest.
Upvotes: 3
Reputation: 1335
you could use something like this:
List<stat> statList = new List<stat>();
...
var selectedItem = statList
.OrderBy(item => item.date)
.Select(l => l.last());
or you could use OrderByDecending()
instead
Upvotes: 0