Lambda在粗糙的层次结构中查找对象(或更改对象模型)

时间:2019-04-04 22:36:15

标签: c# .net razor 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字段将它们联系起来。我认为这可以解决问题,但是我不确定这是否会使其他方面的工作更加困难。

1 个答案:

答案 0 :(得分:1)

递归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);