c#将SQL语句转换为lambda表达式
本文关键字:lambda 表达式 转换 语句 SQL | 更新日期: 2023-09-27 18:16:53
我有这样的SQL语句:
SELECT questionNo , ActivityID ,GROUP_CONCAT(CONCAT(Question, '[' , Answer , ']')
SEPARATOR ' ')AS joined
FROM question
GROUP BY QuestionNo , ActivityID
LIMIT 0,30
但我使用实体框架MySQL和我的大多数类文件方法是lambda,我如何将其转换为lambda表达式?
下面 -------------
public IList<Model.question> GetList()
{
IList<Model.question> lstRecords = context.questions.ToList();
return lstRecords.GroupBy(x => new { x.QuestionNo, x.ActivityID }).Select(g => new { QuestionNo = g.Key.QuestionNo, ActivityID = g.Key.ActivityID, joined = string.Join(" ", g.Select(i => i.QuestionContent + "[" + i.Answer + "]"))});
}
如果我想获得它的列表,我应该如何写它?它说不能将ienumerable类型转换为ilist
try below
var result = question.GroupBy(x=>new{x.QuestionNo , x.ActivityID})
.Select(g=> new {QuestionNo= g.Key.QuestionNo,
ActivityID= g.Key.ActivityID,
joined = string.Join(" ", g.Select(i=>i.Question+ "[" + i.Answer +"]"))})
.Take(30);
如果你想从方法中返回这个,你可以像下面这样创建一个新类
public class Question
{
public int QuestionNo {get;set;} //change the type accordingly
public string ActivityID {get;set;} //change the type accordingly
public string joined {get;set;} //change the type accordingly
}
并将方法更改为:
public IList<Question> GetList()
{
IList<Question> lstRecords = context.questions.GroupBy(x => new { x.QuestionNo, x.ActivityID })
.Select(g => new Question(){
QuestionNo = g.Key.QuestionNo,
ActivityID = g.Key.ActivityID,
joined = string.Join(" ",
g.Select(i => i.QuestionContent + "[" + i.Answer + "]"))})
.Take(30)
.ToList();
}