0

在 c# 中,我有 2 个列表。

第一个列表是这样的:

respondent.PrescreenerResponses[i].Response[j] = {[12, some response]}

第二个列表是这样的:

projects.Prescreeners[i].Questions[j] = {Prescreener Questions: Question}

我想要做的是创建一个可能像这样的列表:

Prescreeners[i].Responses[j]
Prescreeners[i].Questions[j]

我的代码虽然有点错误:

foreach (var screener in respondent.PreScreenerResponses)
{
    var responses = screener;
}

foreach (var screener in project.PreScreeners)
{
    var questions = screener;
}

List<string> prescreenerResponses = new List<string>();
prescreenerResponses.Add(questions);

它告诉我问题在当前上下文中不存在。当我尝试使用它时,响应也是如此。我很确定它是错误的数据类型,但不确定它还会是什么?

4

4 回答 4

4

我很确定这是错误的数据类型

不,是范围。您在各自的块中声明var responsesand 。一旦控制离开这些块,变量就不再存在了。var questionsforeach

首先声明它们:

IEnumerable<PrescreenerResponses> responses = new List<PrescreenerResponses>;

foreach (...)
{
    responses.Add(...)
}

无论如何,AddRange()如果您声明responses为,您也可以调用List,因此您可以跳过循环:

responses.AddRange(respondent.PreScreenerResponses);

更可取的是创建一个 DTO:

class QuestionAndAnswer
{
    public PreScreener Question { get; set; }

    public PreScreenerResponse Response { get; set; }
}

并使用带计数器的循环来填充List<QuestionAndAnswer>

var result = new List<QuestionAndAnswer>();

for (int i = 0; i < projects.Prescreeners.Count; i++)
{
    result.Add(new QuestionAndAnswer
    {
        Question = projects.Prescreeners[i],
        Answer   = respondent.PrescreenerResponses[i],
    });
}
于 2013-11-01T15:25:11.627 回答
1

像这样试试

    List<string> prescreenerResponses = new List<string>();
    foreach (var screener in respondent.PreScreenerResponses)
    {
        var responses = screener;
    }

    foreach (var screener in project.PreScreeners)
    {           
        prescreenerResponses.Add(screener);
    }
于 2013-11-01T15:24:32.670 回答
0

您正在访问在范围之外声明的变量“问题”,

尝试这个:

 List<string> prescreenerResponses = new List<string>();
foreach (var screener in respondent.PreScreenerResponses)
        {
            var responses = screener;
        }

        foreach (var screener in project.PreScreeners)
        {
            var questions = screener;
            prescreenerResponses.Add(questions);
        }
于 2013-11-01T15:26:26.010 回答
0

这是因为在您的循环中声明了“问题”。你可以试试下面的代码:

    private class QuestionAndResponses 
    {
         public List<Response> Responses {get;set;}
         public List<Question> Questions {get;set;}
    }

    List<QuestionAndResponses> prescreenerResponses = new List<QuestionAndResponses>();
    for (var i = 0; i < project.preScreeners.Count(); i++) 
    {
         prescreenerResponses.Add(new QuestionAndResponses ()
         {
               Responses = new List<Response>(project.preScreenerResponses[i].Response),
               Questions = new List<Question>(project.preScreeners[i].Questions)
         });
    }
于 2013-11-01T15:27:03.503 回答