0

我有 2 个列表。我想将它们组合成 1 个列表。

问题是两个列表之一只有一个计数大小

firstList.Count = 1

而第二个列表的大小是两个:

secondList.Count = 2

所以我想将这些列表中的机器人组合成 1 个列表。

megaList => firstList {0, Empty},
            secondList {0 , 2}

我这样做的代码不起作用,因为这两个列表的大小不同。我该如何解决?

 List<QuestionAndResponses> megaList = new List<QuestionAndResponses>();
                for (var i = 0; i < firstList.Count(); i++)
                {
                    megaList.Add(new QuestionAndResponses()
                    {
                        Responses = new List<Response>(firstList[i].Response),
                        Questions = new List<Question>(secondList[i].Questions)
                    });
                }

我的模型看起来像这样:

public class QuestionAndResponses
    {
        public PreScreener Question { get; set; }
        public PreScreenerResponse Response { get; set; }
    }
4

2 回答 2

0

我不完全知道你为什么有这两个列表以及你想在那里存储什么。但是只需对您的代码进行简单的更改,为什么您不只是遍历更大的列表呢?

List<QuestionAndResponses> megaList = new List<QuestionAndResponses>();
var biggerList = firstList.Count() > secondList.Count() ? firstList : secondList
for (var i = 0; i < biggerList.Count(); i++)
{
   var response = firstList.Count() >= i+1 ? new List<Response>(firstList[i].Response) : new List<Response>();
   var questions = secondList.Count() >= i+1 ? new List<Question>(secondList[i].Questions) : new List<Question>(); 

   megaList.Add(new QuestionAndResponses()
      {
         Responses = response,
         Questions = questions
      });
}

希望这是你所要求的。

于 2013-11-03T17:16:51.603 回答
0

我认为您的模型可能是错误的,但您会比我更了解这一点。第一个数组中的答案是否属于同一个问题?一个问题可以有多个答案吗?在这种情况下,您的模型可能是:

public class QuestionAndResponses
{
   public PreScreener Question {get; set;}
   public IEnumerable <PreScreenerResponse> Responses {get; set;}
}

var questionAndResponses = new List<QuestionAndResponses>();
foreach (var question in secondList)
{
   questionAndResponses.Add(
            new QuestionAndResponses
           {
              Question = question,
              Responses = firstList.Where(f => f.QuestionId = question.QuestionId)
           });
}

直接扔出去...

于 2013-11-03T17:44:41.313 回答