0

I feel like this has a really simple answer and I just can't get to it, but here's my shot on it after not finding anything related on the internet.
Esentially, I would like to do something like this from javascript in C#:

var abc = ["a", "b", "c"]
var abcd = [...abc, "d"]

"Spreading" the content of the one-dimensional array abc into another one-dimensional array abcd, adding new values during initialization.
Replicating this behaviour in C#, however, won't work as intended:

string[] abc = { "a", "b", "c" };
string[] abcd = { abc, "d" };

The closest I got to replicating this in C# was with Lists, like so:

string[] abc = { "a", "b", "c" };
var abcd = new List<string>();
abcd.AddRange(abc);
abcd.Add("d");

I could've saved a line in the above example by directly initializing the List with the "d" string (the order doesn't matter to me, I'll just be checking if the collection contains a certain item I'm looking for), but using a List is in itself highly inefficient in comparison to initializing an array since I have no intention on modifying or adding items later on.
Is there any way I can initialize a one-dimensional array from other one-dimensional arrays in one line?

3x071c
  • 955
  • 10
  • 40
  • Have a look at existing thread for some ideas [How to create and initialize an array with another array?](https://stackoverflow.com/questions/9917390/how-to-create-and-initialize-an-array-with-another-array) – Pavel Anikhouski Apr 11 '20 at 16:00

2 Answers2

2

If you're looking for a one-liner, you may use the Enumerable.Append() method. You may add a .ToArray() at the end if want the type of abcd to be a string array.

There you go:

string[] abcd = abc.Append("d").ToArray();

Note: The Append() method is available in .NET Framework 4.7.1 and later versions

For .NET Framework 4.7 or older, one way would be to use the Enumerable.Concat() method:

string[] abcd = abc.Concat(new[] { "d" }).ToArray();
string[] abcde = abc.Concat(new[] { "d", "e" }).ToArray();
1

In 1 line:

string[] abc = { "a", "b", "c" };
var abcd = new List<string>(abc) { "d" };

The constructor of a list can take another list.

Guillaume S.
  • 1,515
  • 1
  • 8
  • 21
  • Thats cool and all, but I'd like to avoid using a List because of unnecessary performance cost. I have no intention on changing its size later on, which is why I'm specifically asking if this would be possible with an array (no Lists involved). – 3x071c Apr 11 '20 at 15:53