尝试使用其他查询中的变量对查询进行排序

本文关键字:查询 变量 排序 其他 | 更新日期: 2023-09-27 18:27:16

所以我试着这样做:

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

尝试使用其他查询中的变量对查询进行排序

对不起我的英语。您的代码无法工作,因为在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);
 }