我想使用LINQ执行以下查询:
数据库:
PRODUCTS
代码:
SELECT U.USER_NAME, U.USER_EMAIL, U.USER_PHONE, U.USER_AVATAR, U.ABOUT
FROM USERS AS U
WHERE U.USER_ID = '${user_id}'
SELECT B.PRODUCT_ID
FROM BOOKMARKS_PRODUCTS AS B
WHERE B.USER_ID = '${user_id}'
SELECT P.*
FROM PRODUCTS AS P
WHERE P.PRODUCT_ID = '${product_id}'
答案 0 :(得分:0)
您改编的函数以及我介绍的用于存储结果的额外类:
public class UserRankObject
{
public int Rank { get; set; }
public int UserId { get; set; }
public float AverageScore { get; set; }
}
public UserRankObject GetUserRankObject(int? Student_ID, int? CourseID, int? SemID, int? SubjectID)
{
// TODO: add null checks for arguments, or make them non-nullable.
var scoreCard =
dbcontext.Stu_Result
.Where(u => u.CourseID == CourseID
&& u.SemID == SemID
&& u.SubjectID == SubjectID);
return scoreCard.GroupBy(u => u.UserID)
.OrderByDescending(g => g.Average(u => u.ScoredMarks / u.TotalMarks * 100))
.Select((g, i) => new UserRankObject
{
UserId = g.Key,
Rank = i + 1,
AverageScore = g.Average(u => u.ScoredMarks / u.TotalMarks * 100)
})
.Single(u => u.UserId == Student_ID);
}
用法:
var ranked = new List<UserRankObject>()
{
GetUserRankObject(1022, 109, 3000, 2006),
GetUserRankObject(1021, 109, 3000, 2006)
};
Console.WriteLine("Ranked: \n" + string.Join("\n", ranked.Select(r => $"{r.Rank}. {r.UserId} ({r.AverageScore})")));
/*
Ranked:
1. 1022 (77.5)
2. 1021 (51.66667)
*/
答案 1 :(得分:0)
public GetCalculatePerform(int? Student_ID, int? CourseID, int? SemID, int? SubjectID)
{
var scoreCard = dbcontext.Stu_Result
.Where(u => u.CourseID == CourseID && u.SemID == SemID && u.SubjectID == SubjectID )
.ToList()
.GroupBy(u => u.UserID)
.OrderByDescending(grp => grp.Average(u => u.ScoredMarks))
.Select((grp, i) => new
{
UserId = grp.Key,
Rank = i + 1,
AverageScore = grp.Average(u => u.ScoredMarks)
}).ToList().Single(u => u.UserId == Student_ID);
}
答案 2 :(得分:0)
public class GetCalculatePerform
{
abcEntities dbcontext = new abcEntities();
public UserRankObject tempobj { get; set; }
//********************************************************Performance & Rank Calculation********************************************
public GetCalculatePerform(int? Student_ID, int? CourseID, int? SemID, int? SubjectID)
{
var scoreCard = dbcontext.Stu_Result
.Where(u => u.CourseID == CourseID && u.SemID == SemID && u.SubjectID == SubjectID)
.ToList()
.GroupBy(u => u.UserID)
.OrderByDescending(grp => grp.Average(u => u.ScoredMarks))
.Select((grp, i) => new UserRankObject
{
UserId = grp.Key,
Rank = i + 1,
AverageScore = grp.Average(u => u.ScoredMarks)
}).ToList().Single(u => u.UserId == Student_ID);
// .FirstOrDefault(u=>u.UserId == Student_ID);
this.tempobj = scoreCard;
}
}