Home > other >  How to dynamically name a variable
How to dynamically name a variable

Time:12-06

I would like to dynamically set string variables taken from a database. So instead of setting each variable manually as bellow

String XXX = "123";
String YYY = "456";
String ZZZ = "789";

I would like to set the variables dynamical as follows

Table: DefualtValues

ID Value
XXX 123
YYY 456
ZZZ 789
myDBConnection.Open();
string GetDefualtValuesSQL = "SELECT * FROM DefualtValues";
SQLCommand = new MySqlCommand(GetDefualtValuesSQL, myDBConnection);
dbReader = SQLCommand.ExecuteReader();

while (dbReader.Read())
{
   String dbReader.GetString(0)= dbReader.GetString(1);     
}

myDBConnection.Close();

Console.WriteLine(XXX);
/// Should output 123

CodePudding user response:

As people in the comments mentioned, you can go for something like this:

myDBConnection.Open();
string GetDefualtValuesSQL = "SELECT * FROM DefualtValues";
SQLCommand = new MySqlCommand(GetDefualtValuesSQL, myDBConnection);
dbReader = SQLCommand.ExecuteReader();

IDictionary<string, string> result = new Dictionary<string, string>();

while (dbReader.Read())
{
    result.Add(dbReader.GetString(0), dbReader.GetString(1));
}

myDBConnection.Close();

Console.WriteLine(result["XXX"]);
/// Should output 123
  • Related