【问题标题】:Combining 2 different size lists in C#在 C# 中组合 2 个不同大小的列表
【发布时间】:2013-11-03 17:05:35
【问题描述】:

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

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

firstList.Count = 1

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

secondList.Count = 2

所以我想将这些列表中的 bot 组合成 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; }
    }

【问题讨论】:

  • 你想看到什么结果?
  • 我希望 QuestionAndResponses List 中同时包含 firstList 和 secondList。换句话说,将两个数组组合成一个更大的数组。
  • 什么业务逻辑控制如何将响应与问题相关联?换句话说,回答是否知道他们属于哪个问题?

标签: c# ienumerable


【解决方案1】:

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

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
      });
}

希望这是您的要求。

【讨论】:

    【解决方案2】:

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

    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)
               });
    }
    

    只是把它扔在那里......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-22
      • 2017-08-23
      • 2022-11-11
      • 1970-01-01
      相关资源
      最近更新 更多