Firstly, apologies for the bad question title - not entirely sure if I am asking the correct thing.
Normally I can do the following to access a field:
It is definitely doable but does get alot more complicated. If you want to do a completely dynamic LINQ query you should check out these posts by Scott Hanselman.
You need to use reflection, like this: (Untested)
somevalue = typeof(MyTable).GetProperty(fieldName).GetValue(table, null);
Weirdly I have just been reading something similar on Scott Hanselman's blog, this is to set the where or ordering by a field name in a string but I think the select could be done in the same way. See:
http://www.hanselman.com/blog/TheWeeklySourceCode48DynamicQueryableMakesCustomLINQExpressionsEasier.aspx
The core being something like :
Dim Northwind As new NorthwindDataContext
Dim query = Northwind.Products
.Where("CategoryID=2 And UnitPrice>3")
.OrderBy("SupplierID")
GridView1.DataSource = query
GridView1.DataBind()
It may require some dynamic data references.
In order to do this, you will need to use reflection.
public object GetField(object obj, string fieldName) {
var t = obj.GetType();
var field = t.GetField(fieldName);
return field.GetValue(obj);
}
somevalue = GetField(table, "someFieldName");
This works as long as the field is both instance and public. You'd need to modify the GetField method call slightly if the accessibility was less than public.
If you have string s = "sampleField";
, then you can just use reflection:
object value = table.GetType().GetProperty(s).GetValue(table, null);
If you need the PKID as a string, it is more complex, and you need to use a runtime-generated lambda. Exactly how depends slightly on the implementation - for example, to identify the PK from LINQ-to-SQL, see this answer which looks at the data-contexts metadata.