所以我试着这样做:
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);
}
但是我收到一条错误,说“Method'System.Nullable`1 [System.Int32] GetUserPoints(Int32)'没有支持的SQL转换。”
我知道如何才能让这样的东西起作用吗?
此致
Arseney
答案 0 :(得分: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 where而不是this loop
List<User> users = new List<User>();
foreach (var usr in userResults)
{
if (usr.myPoints > 0)
users.Add(usr);
}