3x071c
3x071c

Reputation: 1006

Initializing a one-dimensional array from other one-dimensional arrays

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?

Upvotes: 0

Views: 60

Answers (2)

41686d6564
41686d6564

Reputation: 19641

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();

Upvotes: 2

Guillaume S.
Guillaume S.

Reputation: 1545

In 1 line:

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

The constructor of a list can take another list.

Upvotes: 1

Related Questions