How can I create a new list as a result of combing two other lists?

Viewed 103

I trying to create a third list which is the result of combining two other lists, but I don't know how.

I've also been working on combining the first element in the first list (names) to the first element in the second list (states) and make them as the first element in the third list (employees).

For example, I would like the first element in the employee list to be as "Michael lives in Oregon".

I would really appreciate it if someone could help me with this. Thank you.

using System;
using System.Collections.Generic;

class Program
{
   static void Main() 
   {
        // Initializing and Declaring the Lists
        List<string> names = new List<string>();
        List<string> states = new List<string>();
        List<string> employees = new List<string>();
    
        // names
        names.Add("Michael");    
        names.Add("Anna");    
        names.Add("Connor");    
        names.Add("Jane");    
        names.Add("Brian");   
    
        // states 
        states.Add("Oregon");
        states.Add("Florida");
        states.Add("New York");
        states.Add("California");
        states.Add("Kentucky");
   }
}
3 Answers

LINQ Zip to the rescue:

var result = names
    .Zip(states, (name, state) => $"{name} lives in {state}")
    .ToList();

You could pull from names by name and index, then use the index to pull the correct value from states.

Then, use string.Format() with arguments to replace the {0} and {1} with name and states[index].

This can be done with linq like so:

List<string> employees = names
  .Select((name, index) => string.Format("{0} lives in {1}", name, states[index]))
  .ToList();

If both Lists have the same length you can loop through one of them and then add both names[i] and states[i] into the new list.

Solution without using Linq:

if (names.Count == states.Count) {
    for (int i = 0; i < names.Count; ++i) {
        employees.Add(names[i] + " lives in " + states[i]);
    }
}
Related