Ben
Ben

Reputation: 2523

Variable string editing

I have a form on which you can select multiple items to create a code.

Eg. if I clicked on "name", it would add that to the string, then if I clicked "age" it would then add that to the string, but if I unchecked "name", it would remove it from the string.

I have no idea of how to go about this. Can someone help?

Upvotes: 0

Views: 67

Answers (3)

cYOUNES
cYOUNES

Reputation: 936

Why not using List? it allows you to add/remove elements easily? if you click on name, just add it to the list, when you uncheck the name, remove it from the list, after that, you can convert your list into a string and use it.

//Add string
var myList = new List<string>();
//After clicking: 
myList.add(clickedElement);
//After uncheck
myList.remove(uncheckedElement);
//At the end, just convert your list to string to use it
var myString = string.Join(" ", myList.ToArray()); 

Upvotes: 0

NeverHopeless
NeverHopeless

Reputation: 11233

Take a List<string> and add/remove items to/from the list. Once you are done, you make a call to string.Join and construct a single string from array.

List<string> items = new List<string>(); // declare globally

private void add(string item)
{
   items.Add(item);
}

private void remove(string item)
{
   items.Remove(item);
}

private string convertArrayToString(string delimiter, List<string> elements)
{
   delimiter = (delimiter == null) ? "" : delimiter;
   return string.Join(delimiter, elements.ToArray());
}

Note:

Giving a priority to List<T> over string[] would be a good decision since, here collection would be resize. Have a look at this discussion which can help you on this.

Upvotes: 1

Sadique
Sadique

Reputation: 22813

Simply use a List.

List<string> myList = new List<string>();
myList.Add("Somestring");

Then you can use the following methods:

myList.Remove or myList.RemoveAll or myList.RemoveAt and so on.

Upvotes: 0

Related Questions