Crossing a string - is there a better way?

I pass a String Array to a function with the code below. The lines in the array are the first part of the email addresses. I need to add domain.com at the end of each line and a "," between each address. I have a working code below, but just wondering if there is a way (better / cleaner / more efficient) to do this?

String toAddress = "";
for (int x = 0; x < addresses.Length; x++)
{
    if (x == (addresses.Length-1))
    {
        toAddress += addresses[x] + "@domain.com";
    }
    else
    {
        toAddress += addresses[x] + "@domain.com,";
    }
}
+4
source share
2 answers

You can use JoinLinq Selectto solve this problem.

string toAddress = string.Join(",", addresses.Select(x => x + "@domain.com"));
+11
source

fubo has the perfect and shortest answer, but here is another way to do it.

string toAddress = null;
addresses.ForEach(x => toAddress += $"{x}@domain.com,");
toAddress = toAddress.Remove(toAddress.Length - 1);
+2
source

Source: https://habr.com/ru/post/1693354/


All Articles