2015-05-20 47 views
1

下面是用戶不可用表。Linq查詢獲得一個月的每日狀態

Id | UserId | StartDate | EndDate 
1 | 100 | 01-02-2015 | 01-03-2015 
2 | 101 | 10-02-2015 | 11-03-2015 
3 | 102 | 09-04-2015 | 11-05-2015 
3 | 100 | 01-05-2015 | 01-09-2015 

我需要顯示在日曆中每天有多少用戶不可用。日曆會一次顯示一個月的數據,並且每天都會顯示不可用用戶的數量。

我如何從每月的每一天的LINQ獲取數據?

回答

0

我認爲這會做

int TotalDayCount = 365; 
DateTime startDay = DateTime.Now; 
var NoOneAvailable = (from x in Enumerable.Range(0, TotalDayCount) 
let myday = startDay.AddDays(x) 
where !datapoints.Any(f => f.start > myday && f.end < myday) 
select myday).ToList(); 
+0

但我需要得到一個月份的數據一個時間只有一整年。 – Fooker

+0

您只需要將totalDayCount更改爲somethnig,如 DateTime.DaysInMonth .... 和startDay即可到月的第一天。 – cechode

0

試試這個代碼(用戶的本地收藏,不是的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(); 

    } 
}