Search code examples
c#asp.net.netconsole

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

Solution

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