c# - Linq 搜索对象列表

标签 c# asp.net-mvc linq

我有这门课:

public class ExamReviewRequested
{
    public List<ExamReviewRequest> Reviews { get; set;}
}

它的 reviews 属性有一个这个类的列表:

public class ExamReviewRequest
{
    public string EventCode { get; set; }
    public bool Requested { get; set; }
}

如何使用 LINQ 搜索特定的 EventCode 并返回带有该 EventCode 的选定 ExamReviewRequest?在我看来,这两个(Row.EventCode 具有我想要搜索的值):

ExamReviewRequest er = ViewBag.ExamReviews.Single(x => x.EventCode == Row.EventCode)

ExamReviewRequest er = ViewBag.ExamReviews.Reviews.FirstOrDefault(x => x.EventCode == Row.EventCode)

返回这个错误:

Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type

我看过几篇关于这个主题的帖子,但无法使其中任何一篇发挥作用。

最佳答案

当您分配 ExamReviews 时到 ViewBag他们变成了dynamic没有类型设置的对象。错误消息告诉您需要先转换它才能使用 Linq。

你能做什么

我看不到你在哪里分配 ViewBag.ExamReviews所以如果它的类型是 IEnumerable<ExamReviewRequest>然后:

var examReviews = (IEnumerable<ExamReviewRequest>)ViewBag.ExamReviews
var examReviewRequest = examReviews.Single(x => x.EventCode == Row.EventCode)

或者如果它是 ExamReviewRequested 类型然后:

var examReviews = (ExamReviewRequested)ViewBag.ExamReviews
var examReviewRequest = examReviews.Requests.Single(x => x.EventCode == Row.EventCode)

你应该做什么

你不应该分配 List<ExamViewRequest>/ExamReviewRequestedViewBag .这样你可以这样做:

// Code to set model previous
var examReviewRequested = model.ExamReviews.Single(x => x.EventCode == Row.EventCode);

在哪里model类型为 ExamReviewRequested

关于c# - Linq 搜索对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32868755/

相关文章:

c# - 延迟加载已关闭。使用 .Include() 时,子对象仍会递归加载。

c# - LINQ to SQL 中的内部连接不起作用

javascript - 为什么我不能在我的 View 中引用 JavaScript 文件?

c# - 如何使用 Entity Framework 6 在 ASP.NET MVC 5 中保存自定义模型?

Asp.net MVC 关于 n 层的问题

c# - 如何从 HTTP 流中组装 pdf?

c# - 在unity3d中围绕游戏对象旋转相机

javascript - asp.net mvc 6 web api + Angular 资源帖子数组作为对象属性

c# - 抽象索引遍历的优雅方式

LINQ 到 SQL 插入