gpt4 book ai didi

c# - Linq lambda 实体,不包含定义

转载 作者:太空宇宙 更新时间:2023-11-03 20:14:49 25 4
gpt4 key购买 nike

我这里有这个查询代码:

//Get all records based on ActivityID and TaskID.
public IList<Model.questionhint> GetRecords1(int listTask, int listActivity)
{
IList<Model.questionhint> lstRecords = context.questionhints.ToList();
return lstRecords.GroupBy(x => new { x.QuestionNo, x.ActivityID, x.TaskID }).Where(a => a.TaskID == listTask && a.ActivityID == listActivity).ToList();
}

错误在于.Where 语句,它表示不包含ActivityIDTaskID 的定义。

完整错误:

'System.Linq.IGrouping' does not contain a definition for 'ActivityID' and no extension method 'ActivityID' accepting a first argument of type 'System.Linq.IGrouping' could be found (are you missing a using directive or an assembly reference?)

我在查询语句方面很弱,基本上我想从数据库中检索记录,其中 activity id = something 和 task id = something 并按 questionNo, activityId 和 Task ID 对它们进行分组。

最佳答案

这里最简单的修复是:在分组之前过滤(where);这也将减少分组必须做的工作:

return context.questionhints
.Where(a => a.TaskID == listTask && a.ActivityID == listActivity)
.GroupBy(x => new { x.QuestionNo, x.ActivityID, x.TaskID })
.ToList();

如前所述,它在您的原始代码中不起作用的原因是 GroupBy返回一系列 groups - 每个组都有一个 .Key (你的匿名类型)本身就是一个 IEnumerable<T>该组中项的顺序。

但是!您的方法声称返回 IList<Model.questionhint> ;您的分组数据不是,也永远不会是 IList<Model.questionhint> - 这将是一个 IList<IGrouping<{some anonymous type, Model.questionhint>> .所以:如果您声称它是 IList<Model.questionhint>,您不能这样分组- 由于分组是匿名类型,您无法更改返回类型以匹配。您有两个选择:

  • 不分组
  • 按可声明的内容(自定义类型或 Tuple<...> )分组,并更改返回类型以匹配

例如:

public IList<IGrouping<Tuple<int,int,int>,Model.questionhint>>
GetRecords1(int listTask, int listActivity)
{
return context.questionhints
.Where(a => a.TaskID == listTask && a.ActivityID == listActivity)
.GroupBy(x => Tuple.Create(x.QuestionNo, x.ActivityID, x.TaskID))
.ToList();
}

关于c# - Linq lambda 实体,不包含定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17586823/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com