2012-02-01 79 views
0

以下代碼有效,但它不是一個很好的代碼。 (低性能)Linq to Sql查詢 - 更好的解決方案(優化)

我有一本有價值和關鍵字的字典。

首先我去槽每個存在的web代碼。然後我加載列表中的所有參與者(其中web代碼等同於foreach中的實際web代碼)。在那之後,我添加了數據(webcode的參數和參與者的數量到詞典中)。

 Guid compID = Guid.Parse(wID); 
     ChartModel webcodes = new ChartModel(); 
     webcodes.Title = "Webcodes Statistics"; 
     webcodes.Data = new Dictionary<string, int>(); 

     var webcodesData = db.t_Webcode; 

     foreach (var w in webcodesData) 
     { 
      var wData = db.t_Participant.Where(t => t.FK_Competition == compID && t.Webcode == w.Webcode); 

      if (wData.Count() != 0) 
       webcodes.Data.Add(w.Parameter, wData.Count()); 
     } 

     ViewBag.Webcodes = webcodes; 

TIA

回答

0

你需要沿着這些路線的東西:

webcodes.Data = (from w in db.t_Webcode 
     join p in db.t_Participant on w.Webcode equals p.Webcode 
     where p.FK_Competition == compID 
     group w by w.Parameter into g 
     select new { g.Key, Count = g.Count() }).ToDictionary(); 

我無法測試,但就是查詢您需要的類型。

0

這將假設您在數據庫中定義了關係,並且您的LINQ to SQL數據上下文知道它們。如果沒有,您需要手動加入tWeb代碼中的t_Participants。

這應該在1個單獨的SQL查詢中執行,而不是在tWebcode中每行1個查詢。

var webcodesAndNoOfParticipants = 
    from webcode in db.tWebcode 

    // Define number of participants for this webcode 
    let numberOfParticipants = webcode.t_Participants.Count(participant => participant.FK_Competition == compID) 

    where numberOfParticipants > 0 
    select new { 
     WebcodeParameter = webcode.Parameter, 
     NoOfParticipants = numberOfParticipants 
    }; 

webcodes.Data = webcodesAndNoOfParticipants.ToDictionary(x => x.WebcodeParameter, x => x.NoOfParticipants);