Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the Columns from a WebMatrix Query?

Tags:

c#

webmatrix

The title is pretty self-explanitory, and it seems like it should be an easy task, but everything I've tried has not worked:

Here's my code, which works fine, but the table is variable, so I need to know the Columns it comes back with:

var data = db.Query("SELECT * FROM " + Table);

Here's a list of techniques 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's got to be a more elegant way, right?

I'd like to end up with a List<String> of the Column Names.

like image 995
Travis Heeter Avatar asked Dec 09 '25 17:12

Travis Heeter


1 Answers

List<String> cols = data.First().Columns;


It turns out the Columns Propery is an IList<string> type.

However, it is a property of an individual row of the data result (a row is a DynamicRecord data type), so it is unfortunately inaccessible from the result Object (data in my example). To access it, you need to get a single row, and .First() seems to be a pretty easy way to do that.

Here's my whole 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;
like image 65
Travis Heeter Avatar answered Dec 12 '25 07:12

Travis Heeter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!