Mh_Shiro
Mh_Shiro

Reputation: 11

How to pull from a static string array

static string[] myFriends = new string[] {"Robert","Andrew","Leona","Ashley"};

How do I go about pulling the names from this static string array, so that I can use them separately on different lines? Such as:

Robert is sitting in chair 1

Andrew is sitting in chair 2

Leona is sitting in chair 3

Ashley is sitting in chair 4

I'm guessing I would have to assign them to values, then in a WriteLine Command, I would input {1}, {2}, {3} etc. for each corresponding name?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Friends
{
class Program
{
    public void count(int inVal)
    {
        if (inVal == 0)
            return;
        count(inVal - 1);

        Console.WriteLine("is sitting in chair {0}", inVal);
    }

    static void Main()
    {
        Program pr = new Program();
        pr.count(4);
    }

    static string[] myStudents = new string[] {"Robert","Andrew","Leona","Ashley"};

}
}

I want to add the names to the "is sitting in chair" line.

Upvotes: 0

Views: 144

Answers (2)

jglouie
jglouie

Reputation: 12880

I think the for or foreach as @TGH mentions is the way to go. It's not a good use of recursion, though it sounds like a textbook exercise instead of industrial use of recursion anyway.

If you want to fix yours as-is, using recursion, change the method to:

public void count(int inVal)
{
    if (inVal == 0)
        return;
    count(inVal - 1);

    // arrays are 0-based, so the person in chair 1 is at array element 0
    Console.WriteLine("{0} is sitting in chair {1}", myStudents[inVal-1], inVal);
}

Upvotes: 1

Pradeep
Pradeep

Reputation: 443

Use Linq extension to simpify the code to :

int chairNo =1;
myFriends.ToList().ForEach(x =>  Consol.WriteLine(string.Format("{0} is sitting in chair {1}", x, chairNo++)));

Remember to put following on top; using System.Linq;

Upvotes: 0

Related Questions