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?

1

2 Answers 2

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();
Sign up to request clarification or add additional context in comments.

1 Comment

Exactly what I was looking for!
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.

1 Comment

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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.