简体   繁体   中英

C# Add strings together

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 }))));

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");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM