Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I add a string to each string in an array without using a for loop?

Tags:

c#

Can this be achieved without the for loop?

I know it'd involve interation behind the scenes but I wanted a concise one-liner if possible.

    static void Main(string[] args)
    {
        string[] strings = new string[] { "foo", "bar", "foobar" };
        for(int i = 0; i < strings.Length; i++)
        {
            strings[i] = strings[i] + "!";
        }
        Console.WriteLine(string.Join(" ", strings));
    }

Each string in my array (foo, bar, foobar) gets an exclamation mark! Output: foo! bar! foobar!

(although the display bit isn't important here, I really want the string ! added to each element in the array)

like image 564
jamheadart Avatar asked Nov 28 '25 23:11

jamheadart


1 Answers

try

static void Main(string[] args)
{
    string[] strings = new string[] { "foo", "bar", "foobar" };
    var strings1 = strings.Select(xx=>xx + "!!");       
    Console.WriteLine(string.Join(" ", strings1));
}
like image 147
Anu Avatar answered Nov 30 '25 12:11

Anu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!