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.

1

3 Answers 3

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

Comments

1

You can use Array.Copy:

Array.Copy(StringList.ToArray(), 0, StringArray, 2, StringList.Count);

2 Comments

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 - You could define the array like new string[StringList.Count + fixNumberOfSingleStrings].
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();

Comments

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.