2014-03-28 143 views
0

您好,我有一個linq查詢下方該組購買月份和該月的總和。查詢有效,但是當某個月沒有購買時,我希望它在該月份返回0。在那一刻它只是蹦蹦跳跳那個月。例如,如果只有半年LINQ查詢只返回6條,我想返回購買12中,其中6將等於0LINQ sum和groupby並返回空記錄?

    var purchaseData = (from p in db.Purchases 
           where p.UserId == WebSecurity.CurrentUserId 
           group p by new {p.DateBought.Value.Month} into g 
           select new {g.Key.Month, Sum = g.Sum(p => p.Price)}).ToArray(); 

      string[] myArray = new string[12]; 

      for (int i = 0; i < purchaseData.Length; i++) 
      { 
       myArray[i] = purchaseData[i].Sum.ToString(); 
      } 

我將如何做到這一點?

感謝

回答

0

創建個月

var months = Enumerable.Range(1,12); 

左連接到您的購買數據,你可以直接把結果數組中

string[] myArray = (from month in months 
         from p in purchaseData.Where(x => month == x.Month).DefaultIfEmpty() 
         select p == null ? "0" : p.Sum.ToString()).ToArray()