Reputation: 103
I would like to know the most efficient way of creating new arrays from the content of other arrays.
I have several arrays of strings of the type:
public readonly string[] Taiwan = { "TW", "TWO" };
public readonly string[] Vietnam = { "HM", "HN", "HNO" };
public readonly string[] Korea = { "KQ", "KS" };
public readonly string[] China = { "SS", "SZ" };
public readonly string[] Japan = { "T", "OS", "NG", "FU", "SP", "Q", "OJ", "JNX", "IXJ", "KAB", "JA", "JPx" };
It would be possible to create now a new array of string in a similar way to this?
public readonly string[] ASIA = { Taiwan, Vietnam, Korea, China, Japan};
That would contain all the strings included in the other arrays.
Upvotes: 7
Views: 668
Reputation: 9790
You might want to create a jagged array like this:
string[][] ASIA = new string[][] { Taiwan, Vietnam, Korea, China, Japan };
Upvotes: 0
Reputation: 3231
You can also use aggregate and union to accomplish this if you want only unique values in the string array
ASIA = ( (new IEnumerable<string>[ ] {
Taiwan , Vietnam , Korea , China , Japan
} )
.Aggregate ( ( a , b ) => a.Union ( b ) )
.ToArray();
Upvotes: 0
Reputation: 203825
You can take your attempt, which generates an array of arrays, and then flatten it using SelectMany
back down into an array of strings.
public readonly string[] ASIA = new[] { Taiwan, Vietnam, Korea, China, Japan}
.SelectMany(countryCode => countryCode )
.ToArray();
Upvotes: 8
Reputation: 50235
string[] ASIA = new []{ Taiwan, Vietnam, Korea, China, Japan}
.SelectMany(s => s) // not entirely sure what these abbreviations are...
.ToArray();
Upvotes: 10
Reputation: 2378
you can concat two arrays.
string[] newArray = arrA.Concat(arrB).ToArray();
I also think that in your case you may probably want to consider a different type of data structure. I think a dictionary might be a good fit.
Dictionary<string, string[]> Asia = new Dictionary<string, string[]>();
The Key can be the Country, and the value can be the array for that country.
Upvotes: 6