Start learning free

LESSON 148 OF 347 · LOOPING OVER ARRAY INDICES

Get Full Names in C#: Looping Over Two Arrays by Index

Practice Read the full explanation

Given two arrays of strings named firstNames and lastNames, return an array containing the full names (separated by one space)

Example:

Input:   firstNames = ["John","Andy","Mary"]
         lastNames = ["Doe","Smith","Johnson"]

Output:  ["John Doe", "Andy Smith", "Mary Johnson"]
STEP 1 OF 5
    Ctrl + Enter to check

    C# · LOOPING OVER ARRAY INDICES

    Get Full Names in C#, explained

    Problem overview

    The method GetFullNames receives two string arrays of the same length, firstNames and lastNames. The first name at position i belongs with the last name at position i. The method returns a List<string> of the full names, each one a first name, a single space and a last name, in the original order.

    For firstNames = ["John", "Andy", "Mary"] and lastNames = ["Doe", "Smith", "Johnson"], the result is ["John Doe", "Andy Smith", "Mary Johnson"].

    Approach: walk both arrays with one index

    A foreach loop visits the elements of one collection, so it can't pair up two arrays. What links the arrays is the position, so the loop uses an index i and reads firstNames[i] and lastNames[i] together. This kind of loop is also the way to go whenever you need to know where you are in an array.

    The result's size isn't something the method has to compute up front: a List<string> starts empty and grows with each Add. An array would need its length fixed when it is created, which is possible here, since the result has as many items as firstNames, but the list keeps the code simpler.

    Step by step

    1. Create an empty list called names to collect the results.
    2. Loop over the indices of firstNames. The index runs from 0 up to, but not including, firstNames.Length. The loop uses firstNames to decide how many passes to make, because the two arrays are the same length.
    3. Build the full name. Join the first name, a single space and the last name with +. The space is its own string, " ", placed between the two names.
    4. Add the name to the list. Add appends at the end, so the output order matches the input order.
    5. Return the list after the loop, once every pair has been handled.

    The solution in C#

    class Solution {
        public List<string> GetFullNames(string[] firstNames, string[] lastNames) {
            List<string> names = new List<string>();
            for (int i = 0; i < firstNames.Length; i++) {
                string name = firstNames[i] + " " + lastNames[i];
                names.Add(name);
            }
            return names;
        }
    }
    

    A few C# details are worth knowing:

    • Length versus Count. Arrays have a Length property, while a List<T> has Count. Neither takes parentheses. The parameters here are arrays, so the loop uses Length.
    • Strings are immutable. The + operator doesn't modify either name. It creates a new string holding both parts, and that new string goes into the list. The original arrays stay unchanged.
    • Interpolation is an alternative. $"{firstNames[i]} {lastNames[i]}" builds the same string, and many people find it easier to read. The result is identical.
    • Method names are PascalCase. The lesson's method is GetFullNames, with a capital G and capital N. C# is case-sensitive, so getFullNames would be a different name.

    Complexity

    Time: O(n), where n is the number of names. The loop runs n times, and each pass builds one short string and appends it. Appending to a List<T> takes constant time on average. The list occasionally has to enlarge its internal storage, but that cost is spread over many appends.

    Space: O(n) for the returned list and the strings it holds. Besides the output, the method keeps only the index and one temporary string.

    Edge cases and common mistakes

    • Empty arrays. The loop condition 0 < 0 is false at once, so the method returns an empty list. This needs no special case.
    • Arrays of different lengths. The lesson promises matching arrays. If lastNames were shorter, lastNames[i] would eventually throw an IndexOutOfRangeException.
    • Forgetting the space. firstNames[i] + lastNames[i] produces JohnDoe. The expected output has exactly one space between the names.
    • Using <= in the loop. The last valid index is Length - 1. With <=, the final pass reads one slot past the end and throws.
    • Returning an array type. The method's return type is List<string>, so the result must be a list. Returning string[] doesn't compile.
    • Using == or reference comparison to check results. Two lists are never equal just because they hold the same names. Compare the contents, for example by printing string.Join(", ", names).

    Testing

    • ["John", "Andy", "Mary"] with ["Doe", "Smith", "Johnson"] gives John Doe, Andy Smith, Mary Johnson.
    • One name each, ["Ana"] and ["Lee"], gives Ana Lee.
    • Two empty arrays give an empty list.
    Keep going with C#About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free