如何使用LINQ选择两级深度的对象值



我有以下类:

表单

public class Form
{
public string id { get; set; }
public IEnumerable<Section> sections { get; set; }
}

部分

public class Section
{
public int id { get; set; }
public string name { get; set; }
public bool validated { get; set; }
public IEnumerable<Question> questions { get; set; }
}

问题

public class Question
{
public int id { get; set; }
public int required { get; set; }
}

我希望能够搜索表格中每个部分中的问题,检查Required是否设置为1或0,并收回所需的每个问题。

我真的不知道该怎么做。目前我有这个:

List<Question> requiredQuestions = 
root.form.sections
.Where(x => x.questions.Where(y => y.required == 1))

但是上面的代码给出了语法错误。我仍然觉得林有点困惑,有人能帮我吗。

您可以使用SelectMany获取所有问题,然后过滤required属性:

List<Question> requiredQuestions = root.form.sections
.SelectMany(section => section.questions)
.Where(question => question.required == 1)
.ToList();

最新更新