Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

365
Visualizações
Combining contents of 2 lists in C#

I just started learning C#. I want to combine 2 lists and return the output. For example:

List 1 = Peter, Tony, Steve
List 2 = Parker, Stark, Rogers

Final List/Output:
Peter Parker
Tony Stark
Steve Rogers

Here is my codes:

using System;
using System.Collections.Generic;
using System.Linq;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            var projectTeam = "Group Avengers";
            Console.WriteLine("Avengers Assemble");

            string[] firstNames = {"Peter", "Tony", "Steve"};
            string[] lastNames = {"Parker", "Stark", "Rogers"};
            IList<string> combinedNames = new List<string>();

            foreach (string firstName in firstNames)
            {
                foreach (string lastName in lastNames)
                {
                    Console.WriteLine(firstName + lastName);
                }
            }
        }
    }
}

Actual Output:

Avengers Assemble
PeterParker
PeterStark
PeterRogers
TonyParker
TonyStark
TonyRogers
SteveParker
SteveStark
SteveRogers

Expected Output:

Avengers Assemble
Peter Parker
Tony Stark
Steve Rogers
over 4 years ago · Santiago Trujillo
6 Respostas
Responde à pergunta

0

In your code you need only one loop and it should be for, not foreach

        for (var i = 0; i< firstNames.Length; i++)
        {
            string firstName = firstNames[i];
            string lastName = lastNames[i];
            Console.WriteLine(firstName + lastName);
        }

You can also replace this with IEnumerable.Zip (https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.zip?view=net-6.0)

        firstNames
            .Zip(lastNames, (first, last) => first + last)
            .ToList()
            .ForEach(x=>Console.WriteLine(x));

Please note that both approaches assumes that both firstNames and lastNames has the same number of elements.

over 4 years ago · Santiago Trujillo Relatório

0

This can be done with LINQ Zip():

var fullNames = firstNames.Zip(lastNames, (first, last) => $"{first} {last}")

Zip takes the two lists and runs through both of them simultaneously, applying the function to each pair.

over 4 years ago · Santiago Trujillo Relatório

0

You could use a for-loop and access the lists via index:

for(int i = 0; i < Math.Min(firstNames.Length, lastNames.Length); i++)
{
    Console.WriteLine(firstNames[i] + lastNames[i]);
} 

better would it be to store the two related information in a common class, for example Avenger with properties FirstName and LastName.

Another way to link two related lists is LINQ's Zip:

var zippedAvengers = firstNames.Zip(lastNames, (f,l) => f + " " + l);
foreach(string name in zippedAvengers)
    Console.WriteLine(name);
over 4 years ago · Santiago Trujillo Relatório

0

If you alter the loop:

    for (int i=0; i < firstNames.Count; i++)
    {
         Console.WriteLine(firstNames[i] + " " + lastNames[i]);
    }

It'll work.

As a side note - in newer versions on .NET you can simplify the concatenation with $"{firstNames[i]} {lastNames[i]}"

Plus, the .Zip solution (as proposed by Serg):

firstNames
   .Zip(lastNames, (first, last) => first + " " + last)
   .ToList()
   .ForEach(x=>Console.WriteLine(x));

Would be more efficient

over 4 years ago · Santiago Trujillo Relatório

0

What you are doing is you're matching every element of the first list with every element of the second list. But what you wanna do, if I get you right, is to match the first element of the first list with the first element of the second list.

In order to do that, I won't give you the code so you can learn but I can show you where to go :

  1. Make sure your lists are both the same size, otherwise you will get an exception trying to access an inexisting index
  2. Use for loop instead of foreach, they are less instinctive but more useful in this situation. For each index of the two lists, make the same index of the third list (the result) correspond to the concatenation of the two, for example :
result[0] = firstList[0] + secondList[0];

(In order to have a space between the two, you must add a space between the first and the second list item)

over 4 years ago · Santiago Trujillo Relatório

0

You are running two for loops for no reason. Just run one single loop from i = 0 to i = 3(not included).Then you can pick the ith element from both the lists. Example. for i = 0, firstNames[0] = "Peter" lastNames[0] = "Parker" You can print

Console.WriteLine(firstNames[i] + " " + lastNames[i]);

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda