2014-10-20 66 views
0

所以我試着這樣做:嘗試使用一個變量來自不同的查詢命令查詢

public List<User> GetLeaderBoard() 
     { 
      SuperGoalDataClassesDataContext myDB = new SuperGoalDataClassesDataContext(); 
      var userResults = (from u in myDB.Users 
           orderby (GetUserPoints(u.userID)) 
           select u).Take(100); 
      List<User> users = new List<User>(); 
      foreach (var usr in userResults) 
      { 
       if (usr.myPoints > 0) 
        users.Add(usr); 
      } 
      return users; 
     } 

     public int? GetUserPoints(int userId) 
     { 
      SuperGoalDataClassesDataContext myDB = new SuperGoalDataClassesDataContext(); 
      var codeResults = (from tc in myDB.TriviaCodes 
           where tc.userID == userId 
           select tc); 
      return codeResults.Sum(cd => cd.pointsGained); 
     } 

但我發現了一個錯誤說「法「System.Nullable`1 [System.Int32] GetUserPoints(Int32)'不支持對SQL的轉換。「

任何想法我怎麼能得到這樣的工作?

問候,

Arseney

回答

1

我爲我的英語很抱歉。你的代碼不工作,因爲在LINQ to SQL中你不能使用許多上下文。你有很多備選方案。 例如與子查詢一對一連接。

public List<User> GetLeaderBoard() 
{ 
return (from u in myDB.Users 
     select new { 
        User = u, 
        Sum = (from tc in myDB.TriviaCodes 
          where tc.userID == u.userID 
          select c).Sum(p => p == null ? 0 : p.pointsGained) 
        }) 
.OrderBy(g => g.Sum) 
.Select(g => g.User) 
.Take(100) 
.Where(u => u.myPoints > 0) 
.ToList(); 
} 

,或者使用串聯和分組

public List<User> GetLeaderBoard() 
{ 
return (from u in myDB.Users 
     join tc in myDB.TriviaCodes on u.userID equals tc.userID into gj 
     from subtc in gj.DefaultIfEmpty() 
     group new { u, subtc } by u into g 
     select g) 
.OrderBy(g => g.Sum(p1 => p1.subtc == null ? 0 : p1.subtc.pointsGained)) 
.Select(g => g.Key) 
.Take(100) 
.Where(u => u.myPoints > 0) 
.ToList(); 
} 

我用where條件,而不是這個循環

List<User> users = new List<User>(); 
foreach (var usr in userResults) 
{ 
    if (usr.myPoints > 0) 
    users.Add(usr); 
} 
+0

好吧,我會嘗試... – steryd 2014-10-20 20:41:41

+0

這完美地工作,無須解釋:) 除了事實我需要它OrderByDescending;) 謝謝! – 2014-10-20 21:17:45