Patrick Patrick - 6 months ago 21
C# Question

Update variable dynamically based on variable from UI

I have the following array initialized in C# code. data1, data2, data3 as manually written in the code to assign it to 'row' as shown below.

string[] row = new string[] { type, data1, data2, data3, shares };

Instead of coding it manually, I want to dynamically assign. To ensure that happens, I take the value of a variable from the UI and assign it to a C# variable like this.

var change_data = "data1, data2"

So for example, I should be able to change the variable 'row' as follows:

string[] row = new string[] { type, data1, data2, shares };

Now another example.

var change_data = "data1";

This should update row as follows too.

string[] row = new string[] { type, data1, shares };


As mentioned in the comments, because of arrays having a fixed length, you'd be better served with using some sort of a collection. Blorgbeard's answer uses a Dictionary<K,V> - another way is to use a List<T>.

What you can do is wrap a List inside a method to start your list off with your first value, insert your input values, and add the final value:

Assume the value of input below is data1, data2:

public static List<string> CreateRowData(string input) {
    var returnList = new List<string> { "type" };

    var inputs = input.Split(',').Select(s => s.Trim());

    foreach (var item in inputs) {


    return returnList;

The above turns: