c# - Lambda 在参差不齐的层次结构中查找对象(或更改对象模型)
问题描述
当层次结构参差不齐时,我无法弄清楚如何构造 lambda 来查找节点。我正在辩论将对象模型更改为不衣衫褴褛,或者在以下相同的情况下询问是否有人可以帮助解决 lambda。
假设我有一个调查对象,它有一个问题对象列表,每个问题都有一个响应对象列表,问题是一个响应可以导致另一个问题。我不知道如何构建 lambda 来搜索调查中的所有问题,以及所有可能有问题的回答,直到所有可能路径的末尾。我没有尝试过的是基本上放弃并重新配置对象模型,所以我只有一个简单的问题和响应列表。
public void OnPostAddResponse(int questionid)
{
//find question so we can add response to it
SurveyQuestion q = this.SurveyObject.Questions.First(x => x.QuestionId == questionid);
if (q.ResponseList == null)
{
q.ResponseList = new List<SurveyResponse>();
}
int newid = (q.QuestionId * 1000) + q.ResponseList.Count + 1;
q.ResponseList.Add(new SurveyResponse(newid));
}
public class Survey
{
public string SurveyName { get; set; }
public List<SurveyQuestion> Questions { get; set; }
public Survey()
{
this.SurveyName = "new survey name here";
this.Questions = new List<SurveyQuestion>();
}
}
public class SurveyQuestion
{
public int QuestionId { get; set; }
public string Question { get; set; }
public List<SurveyResponse> ResponseList { get; set; }
public SurveyQuestion() { }
public SurveyQuestion(int id)
{
this.QuestionId = id;
this.Question = "question text for id " + id;
this.ResponseList = new List<SurveyResponse>();
}
}
public class SurveyResponse
{
public int ResponseId { get; set; }
public string Response { get; set; }
public SurveyQuestion NextQuestion { get; set; }
public SurveyResponse() { }
public SurveyResponse(int id)
{
this.ResponseId = id;
this.Response = "response text for id " + id;
}
}
我希望 OnPostAddResponse 能够搜索整个调查对象并找到传入的问题 ID,即使它可能是响应对象下的问题。
或者,应该重新配置对象模型,以便调查具有问题和响应的平面列表,然后通过其 ID 字段连接。我认为这可以解决问题,但我不确定这是否会使其他方面变得更加困难。
解决方案
递归 LINQ 查询:
public static IEnumerable<SurveyQuestion> Flatten(IEnumerable<SurveyQuestion> source)
{
return source.Concat(source.SelectMany(q => Flatten(q.ResponseList.Where(r => r.NextQuestion != null).Select(r => r.NextQuestion))));
}
用法:
var allQuestions = Flatten(survey.Questions);
推荐阅读
- java - 我怎样才能转换到当前类扩展的类
- azure - 参数化 Azure 数据工厂中的连接(ARM 模板)
- jquery - 使用 JQuery 不安全的内联和 CSP 的问题
- android - 如何在 nativescript 插件种子中实现 google play 服务?
- gsoap - gsoap如何防止枚举值的下划线翻译
- ruby - Logstash - 使用 ruby 代码计算持续时间
- fleetboard - 驾驶员分心受限状态如何工作?
- php - Laravel Passport:仅使用用户名而不使用密码登录
- mysql - 将 JobID 从 React&Redux 前端传递到 NodeJS 后端时,req.body.jobId 显示未定义?
- java - 如何解决“如果”总是“真”