2

I want to be able to do something like this below where I select the field based on a variable name. The below doesn't work and i cant find a solution without doing a big switch statement.

var guidId = new Guid("");
var fieldName= "somefield";

var query =
 from c in Financials
 where c.GuidId == guidId 
 select **fieldName**;

Is their a simple way to do this?

Thanks Austin

Austin
  • 197
  • 1
  • 1
  • 4

2 Answers2

2

Try this out:

select c.GetType().GetProperty(fieldName).GetValue(c, null)

I found this on this SO question. If my answer doesn't work for some reason in the query you can just select c and then just put it through the method as shown in the answer to the SO question.

Note: It returns an object, so be careful!

Community
  • 1
  • 1
Corey Adler
  • 15,897
  • 18
  • 66
  • 80
  • After quite a bit of trail and error i managed to get the function on the link to work. Do you know if this will have much effect on performance as i have heard reflection is bad? – Austin Mar 01 '13 at 08:50
0

You could use reflection:

select c.GetType().GetProperty(fieldName).GetValue(c, null);

It's really the only way to get the value of a property by name.

itsme86
  • 19,266
  • 4
  • 41
  • 57