How to get columns from WebMatrix query?
The title is pretty self-taught and it seems like it should be an easy task, but everything I tried didn't work:
Here's my code, which works great, but the table is a variable, so I need to know the columns it returns:
var data = db.Query("SELECT * FROM " + Table);
Here's a list of the methods I've tried:
data.GetType().GetProperties().ToList();
// prints 'Int32 Count' and 'System.Object Item [Int32]'
data.GetDynamicMemberNames()
// Error: '...IEnumerable<dynamic> does not have a definition for GetDynamicMemberNames'
// I also tried using System.Linq and System.Dynamic
I could also iterate through a loop, but there got to be a more elegant way, right?
I would like to get the List<String>
names of the columns.
source to share
List<String> cols = data.First().Columns;
It turns out Columns Propery is a type IList<string>
.
However, this is a property of a separate row of the data result (row is a DynamicRecord data type), so unfortunately it is not available from the Object result ( data
in my example). You need to get one line to access it, and .First()
is a pretty simple way to do it.
Here's all my code in case anyone needs it:
WebMatrix.Data.Database db = new WebMatrix.Data.Database();
db.Open("ConnectionString");
var data = db.Query("SELECT * FROM " + Table);
List<String> cols = data.First().Columns;
source to share