user954021
user954021

Reputation: 33

Linq - vb.net select a column based on a variable

We are returning a set of data from a table and need to select a column based on a variable

Code is

Dim columnNo as Integer = 1

Dim rs as IEnumerable(Of Object) = db.ImportTable

For each rsRow in rs 
Dim columnF1 = rsRow.f1 'where the field name is f1 (this works fine)
Dim columnVariable = rsRow."f" & columnNo 'This line fails

Thanks in anticipation

Upvotes: 1

Views: 346

Answers (1)

mellamokb
mellamokb

Reputation: 56769

For a small performance hit, you can use reflection:

rsRow.GetType().GetProperty("f" & columnNo).GetValue(rsRow)

This dynamically looks up the property by name, and then reflects the value for that property on the given variable. Note that this will throw exceptions at runtime if the property name is invalid.

Upvotes: 1

Related Questions