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
6
Answers
In your code you need only one loop and it should be
for
, notforeach
You can also replace this with
IEnumerable.Zip
(https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.zip?view=net-6.0)Please note that both approaches assumes that both
firstNames
andlastNames
has the same number of elements.This can be done with LINQ
Zip()
:Zip takes the two lists and runs through both of them simultaneously, applying the function to each pair.
You could use a
for
-loop and access the lists via index:better would it be to store the two related information in a common class, for example
Avenger
with propertiesFirstName
andLastName
.Another way to link two related lists is LINQ’s
Zip
:If you alter the loop:
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):
Would be more efficient
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 :
for
loop instead offoreach
, 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 :(In order to have a space between the two, you must add a space between the first and the second list item)
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]);