試試這個代碼(用戶的本地收藏,不是的LINQ to SQL):
class User
{
public int Id;
public int UserId;
public DateTime StartDate;
public DateTime EndDate;
}
class Program
{
static void Main(string[] args)
{
var users = new User[]{
new User { Id = 1, UserId = 100, StartDate = new DateTime(2015,2,1), EndDate = new DateTime(2015,3,1) },
new User { Id = 2, UserId = 101, StartDate = new DateTime(2015,2,10), EndDate = new DateTime(2015,3,11) },
new User { Id = 3, UserId = 102, StartDate = new DateTime(2015,4,9), EndDate = new DateTime(2015,5,11) },
new User { Id = 3, UserId = 100, StartDate = new DateTime(2015,5,1), EndDate = new DateTime(2015,9,11) }
};
var minDate = users.Select(x => x.StartDate).Min();
var maxDate = users.Select(x => x.EndDate).Max();
var counts = Enumerable
.Range(0, Convert.ToInt32((maxDate - minDate).TotalDays))
.Select(x => {
var Date = minDate.AddDays(x);
return new
{
Date,
Count = users.Where(u => Date >= u.StartDate && Date <= u.EndDate).Count()
};
}).Where(x => x.Count > 0)
.ToArray();
}
}
但我需要得到一個月份的數據一個時間只有一整年。 – Fooker
您只需要將totalDayCount更改爲somethnig,如 DateTime.DaysInMonth .... 和startDay即可到月的第一天。 – cechode