0

I have these variables

string a;
string b;
List<string> StringList = new List<string>();
string c;

I would like to define a new string array like so

string[] StringArray = new string[] {a, b, StringList**.METHODHERE** , c} ;

Is there a neat way to convert the list to the array, flatten it, and add the items to the array? Right now I have something like

string[] ar = new string[] { };
ar[0] = a;
ar[1] = b;

for (int i = 0; i < RpsPdfFilenamesList.Count(); i++)
    {ar[i + 2] = RpsPdfFilenamesList.ElementAt(i);}

ar[2 + RpsPdfFilenamesList.Count()] = c;

But im sure theres a fairly basic method out there that im missing that will reduce this code.

Mufasatheking
  • 375
  • 2
  • 6
  • 16
  • 1
    [Do you really need to use an array?](http://stackoverflow.com/questions/434761/array-versus-listt-when-to-use-which) The `List` class [has a method](http://msdn.microsoft.com/en-us/library/z883w3dc(v=vs.110).aspx) for precisely this – James Thorpe Nov 20 '14 at 12:44

3 Answers3

2

You can insert your strings to List first and then make an array of it:

StringList.Insert(0, a);
StringList.Insert(1, b);
StringList.Add(c);
string[] StringArray = StringList.ToArray();
Vsevolod Goloviznin
  • 11,256
  • 1
  • 39
  • 47
1

You can use Array.Copy:

Array.Copy(StringList.ToArray(), 0, StringArray, 2, StringList.Count);
Christoph Fink
  • 21,159
  • 9
  • 62
  • 101
  • This is the kind of thing I was looking for but I cant change the length of an array after its been defined in c# and the length of the list is highly variable. – Mufasatheking Nov 20 '14 at 13:06
  • @Mufasatheking - You *could* define the array like `new string[StringList.Count + fixNumberOfSingleStrings]`. – Corak Nov 20 '14 at 13:24
0

You could use List.CopyTo:

string a = "A"; string b = "B"; string c = "C";
var StringList = new List<string>() { "test1", "test2", "test3" };
string[] StringArray = new string[3 + StringList.Count];
StringArray[0] = a; StringArray[1] = b; StringArray[StringArray.Length - 1] = c;
StringList.CopyTo(StringArray, 2);

Result

A
B
test1
test2
test3
C

Here's a shorter but less efficient approach using LINQ:

StringArray = new[] { a, b }.Concat(StringList).Concat(new[] { c }).ToArray();
Tim Schmelter
  • 411,418
  • 61
  • 614
  • 859