2

im making a speech alias program. Im trying to make it to add commands. You know basically to make a array of strings you do string mystring = "string1","string2"; How am I able to add it just like ,"string3" to make it string mystring = "string1","string2","string3"; Here is my code:

List<string> myCollection = new List<string>();
            myCollection.Add("hello");
            myCollection.Add("test");
            string final = string.Join(",", myCollection.ToArray());
            richTextBox1.AppendText(final);
            sp.LoadGrammar(new Grammar(new GrammarBuilder(new Choices(new String[] { "" + final }))));
8
  • Whats the problem you are running into? Commented Feb 20, 2017 at 1:55
  • @CodingYoshi when I do that I do not get 2 seprete strings. I get 1 string like hello,test Commented Feb 20, 2017 at 1:56
  • You should read How to Ask and then edit your question, based on the How to Ask page, to make it clearer to understand. Commented Feb 20, 2017 at 1:58
  • Are you asking for string[] finals = new [] { "hello", "test" }? Commented Feb 20, 2017 at 1:59
  • 1
    "I need those 2 strings to be coming out sepertly not as 1 string" … "I need to convert it to a string". Which? Do you need it to be separate strings or do you need to convert it to a string? Commented Feb 20, 2017 at 2:30

1 Answer 1

3

The API you are calling requires an array of string. If you know how many strings you will be passing, then do not use a List<string>. This will help you avoid having to convert List<string> to a string[]. This is how it will work:

var myCollection = new string[2];
myCollection[0] = "hello";
myCollection[1] = "test";
sp.LoadGrammar(new Grammar(new GrammarBuilder(myCollection)));

If you are not sure how many strings you will be passing then use a List<string> like this:

var myCollection = new List<string>();
myCollection.Add("hello");
myCollection.Add("test");

Then you need to convert a List<string> to a string[], just call ToArray<string>() on your collection like this:

var myCollectionAsArray = myCollection.ToArray();
sp.LoadGrammar(new Grammar(new GrammarBuilder(new Choices(myCollectionAsArray))));

What do you mean by if you know how many strings you will be passing?

If you were checking some dynamic condition (a condition only known at runtime) to add items to the choices collection, then you will need a List<string>. For example:

var myCollection = new List<string>();

myCollection.Add("hello");
if (someCondition)
{
    // this will only be known at runtime
    myCollection.Add("test");
}
Sign up to request clarification or add additional context in comments.

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.