Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I reference a field in Linq based on a dynamic fieldname

Tags:

c#

linq

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:

MyTables table = dc.MyTables.SingleOrDefault(p => p.id == someId);
somevalue = table.samplefield;

In this instance the variable somevalue would end up having the value of the field samplefield.

Now I have a scenario where I want to populate a variable, but I don't know the name of the table field at design time. I do however, have this fieldname in a string. Is it therefore possible to fetch a value using this string?

Hoping this makes sense!

like image 353
Martin Avatar asked Jan 27 '10 15:01

Martin


1 Answers

You need to use reflection, like this: (Untested)

somevalue = typeof(MyTable).GetProperty(fieldName).GetValue(table, null);
like image 151
SLaks Avatar answered Sep 19 '22 10:09

SLaks