Answer the question
In order to leave comments, you need to log in
Working with Dictionary in c# - how to get data in an array?
Friends, I do not know c# so deeply, so I have to ask for help.
I use someone else's class that I don't understand, but I need this functionality.
When fetching data, their sqlite is applied
public DataTable ExecuteQuery(string query)
{
if (!IsConnectionOpen)
{
throw new SqliteException("SQLite database is not open.");
}
IntPtr stmHandle = Prepare(query);
int columnCount = sqlite3_column_count(stmHandle);
var dataTable = new DataTable();
for (int i = 0; i < columnCount; i++)
{
string columnName = Marshal.PtrToStringAnsi(sqlite3_column_name(stmHandle, i));
dataTable.Columns.Add(columnName);
}
//populate datatable
while (sqlite3_step(stmHandle) == SQLITE_ROW)
{
object[] row = new object[columnCount];
for (int i = 0; i < columnCount; i++)
{
switch (sqlite3_column_type(stmHandle, i))
{
case SQLITE_INTEGER:
row[i] = sqlite3_column_int(stmHandle, i);
break;
case SQLITE_TEXT:
IntPtr text = sqlite3_column_text(stmHandle, i);
row[i] = Marshal.PtrToStringAnsi(text);
break;
case SQLITE_FLOAT:
row[i] = sqlite3_column_double(stmHandle, i);
break;
case SQLITE_NULL:
row[i] = null;
break;
}
}
dataTable.AddRow(row);
}
Finalize(stmHandle);
return dataTable;
}
public class DataRow : Dictionary<string, object>
{
public new object this[string column]
{
get
{
if (ContainsKey(column))
{
return base[column];
}
return null;
}
set
{
if (ContainsKey(column))
{
base[column] = value;
}
else
{
Add(column, value);
}
}
}
}
public class DataTable
{
public DataTable()
{
Columns = new List<string>();
Rows = new List<DataRow>();
}
public List<string> Columns { get; set; }
public List<DataRow> Rows { get; set; }
public DataRow this[int row]
{
get
{
return Rows[row];
}
}
public void AddRow(object[] values)
{
if (values.Length != Columns.Count)
{
throw new IndexOutOfRangeException("The number of values in the row must match the number of column");
}
var row = new DataRow();
for (int i = 0; i < values.Length; i++)
{
row[Columns[i]] = values[i];
}
Rows.Add(row);
}
}
Answer the question
In order to leave comments, you need to log in
Would use a better SQLite provider for standard ADO.NET, like https://system.data.sqlite.org
You can get an array of values from Dictionary through Values. Or an array of KeyValuePair via ToArray(), ToList() or just a foreach loop.
So it looks like something like this:
for (int i = 0; i < dt.Rows.Count; i++)
{
foreach (var value in dt.Rows[i].Values)
{
//Console.WriteLine(value);
}
}
for (int i = 0; i < dt.Rows.Count; i++)
{
foreach (var kv in dt.Rows[i])
{
//Console.WriteLine("Column: " + kv.Key + ", value: " + kv.Value);
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question