SQL statement to linq lambda Orderby

本文关键字:lambda Orderby linq to statement SQL | 更新日期: 2023-09-27 18:20:52

我有这个sql语句:

SELECT QuestionNo,ActivityID,GROUP_CONCT(CONCAT(问题,"[",
答案,']')分隔符'')从问题GROUP BY加入
问题编号,活动ID订单按问题提示ID

我需要把它放在linq lambda中,到目前为止我有

 IList<QuestionHint> lstRecords = context.questionhints.GroupBy(x => new { x.QuestionNo, x.ActivityID, x.TaskID }).ToList().Select(g => new QuestionHint()
        {
            QuestionNo = g.Key.QuestionNo,
            ActivityID = g.Key.ActivityID,
            TaskID = g.Key.TaskID,
            joined = String.Join(" ",
                    g.Select(i => i.QuestionContent + "[" + i.Answer + "]")),
            joinOption = String.Join(" ",
                   g.Select(a => "[" + a.Option1 + "," + a.Option2 + "]"))
        }).Where(x => x.TaskID == listTask && x.ActivityID == listActivity)
            //.Take(50)
           .ToList();
        return lstRecords;

如何添加Orderby?因为当我在查询中使用联接时,检索到的记录是无序的,因为顺序不能保证是有序的。我如何将OrderBy questionHintID(表的主键)添加到上面的lambda中?

SQL statement to linq lambda Orderby

您尝试过.OrderByDescending(questionhints=>questionhint.ID)吗?希望这能有所帮助!!

我想我理解你的意思。可能应该是这样的:(注意OrderBy语句)

var lstRecords = context.questionhints
.Where(x => x.TaskID == listTask && x.ActivityID == listActivity)
.GroupBy(x => new { x.QuestionNo, x.ActivityID, x.TaskID })
.AsEnumerable()
.Select(g => new QuestionHint()
        {
            QuestionNo = g.Key.QuestionNo,
            ActivityID = g.Key.ActivityID,
            TaskID = g.Key.TaskID,
            joined = String.Join(" ",
                       g.OrderBy(q => q.questionHintID)
                        .Select(i => i.QuestionContent + "[" + i.Answer + "]")),
            joinOption = String.Join(" ",
                       g.OrderBy(q => q.questionHintID)
                        .Select(a => "[" + a.Option1 + "," + a.Option2 + "]"))
        })