2

I tried searching by "C# new string array pass dynamic" but could not find anything relevant.

int[] IDs = someMethodCall();
List<string> values = new List<string>();
foreach (int i in IDs)
{
   values.Add(i.ToString());
}
someClass sc = new someClass();
sc.Value = new string[] {  "values.string1", "values.string2", ... };

What I'm trying to do is to pass the strings from values to sc.Value, so I don't have to write them out (since I don't what they'll be beforehand).

sc.Value is a string[] as defined by the class I'm using from an API (not written by me).

What is the best way to do this dynamically? In other words, how to pass in dynamic values to a string[] construction?

3
  • 1
    You should think about if in 2015 you still need to use arrays. Why converting a list into array when you can work with lists directly? Commented Mar 17, 2015 at 21:30
  • Ordered output comes to mind, but I'm not really certain. Commented Mar 17, 2015 at 23:20
  • You're wrong. List semantics is exactly this... Order is guaranteed. And if you want a concrete ordering, SortedSet<T>... Commented Mar 18, 2015 at 6:02

3 Answers 3

2

If I'm not missing something,you can just use ToArray method

sc.Value =  values.ToArray();

BTW, you don't even need to create a list in the first place:

sc.Value = someMethodCall().Select(x => x.ToString()).ToArray();
Sign up to request clarification or add additional context in comments.

2 Comments

Using Select in that manner is really the right way to go. +1 for that :)
This worked well Selman22. Time to brush up on Linq since I come from a database background and I'm new to C#.
0

I'm a little confused by the way you word your questioning, but I think you are trying to send your list to an array, which is easily done using the code below:

        List<string> values = new List<string>();
        sc.Value = values.ToArray();

1 Comment

Thanks, yes I just found ToArray which leads to no error.
0

How about just using the built-in method ToArray:

sc.Value = values.ToArray();

Comes with List, and is an extension method for IEnumerable if you can use LINQ.

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.