I have this dictionary Dictionary<TableKey, string>
where TableKey
is an enum type.
I'm trying to populate the dictionary with data from a DataSet object that I acquire during an sql query
DataSet resultSet = Utils.RunQuery(sqlQuery);
if (resultSet.Tables.Count > 0)
{
foreach (DataRow row in resultSet.Tables[0].Rows)
{
// Makes the dictionary with populated keys from enum
Dictionary<TableKey, string> dic = new Dictionary<TableKey, string>();
foreach (TableKey key in Enum.GetValues(typeof(TableKey)))
dic.Add(key, "");
// the foreach loop in question, which should insert row data into the dic
foreach (TableKey key in Enum.GetValues(typeof(TableKey)))
dic[key] = row[key.GetName()].ToString(); // This line does not work!
// adds dictionary to my list of dictionaries
latestEntryList.Add(dic);
}
}
I'm trying to replace this by using the forloop in the above code.
dic[TableKey.Barcode] = row["Barcode"].ToString();
dic[TableKey.FullName] = row["FullName"].ToString();
dic[TableKey.Location] = row["Location"].ToString();
dic[TableKey.Notes] = row["Notes"].ToString();
dic[TableKey.Category] = row["Category"].ToString();
dic[TableKey.Timestamp] = row["Timestamp"].ToString();
dic[TableKey.Description] = row["Description"].ToString();
EDIT: Maybe there is a way to combine the two foreach loops into one.
EDIT: I need to get the string name of the enum and the key value itself.
public enum TableKey
{
Barcode = 0,
FullName = 1,
Location = 2,
Notes = 3,
Category = 4,
Timestamp = 5,
Description = 6
}
Solution
DataSet resultSet = Utils.RunQuery(sqlQuery);
if (resultSet.Tables.Count > 0)
{
foreach (DataRow row in resultSet.Tables[0].Rows)
{
Dictionary<TableKey, string> dic = new Dictionary<TableKey, string>();
foreach (TableKey key in Enum.GetValues(typeof(TableKey)))
dic.Add(key, row[key.ToString()].ToString());
latestEntryList.Add(dic);
}
}