简体   繁体   中英

LINQ - Accessing a column with the column name as a string parameter

(Similar to this question )

I have tables called 'Questions' and 'FinalFigures':

Questions (QuestionID, Text, FinalFiguresColumnName)
FinalFigures (FinalFigureID, TotalDays, TotalCost, etc, etc)

'FinalFiguresColumnName' would have values like "TotalDays", "TotalCost", etc. Is there a simple way to loop through a set of Questions and have the 'Text' value saved to the corresponding column name on the 'FinalFigures' table?

Ie. instead of:

var item = new FinalFigure();
item.TotalDays = "x";

I need:

var item = new FinalFigure();
// access the column 'TotalDays' with its name as a string, not a property

You can use a bit of reflection to get the property value by the string name of the property instead of directly accessing it.

var value = (int)item.GetType().GetProperty("TotalDays").GetValue(item);

To set the value, simply call SetValue();

item.GetType().GetProperty("TotalDays").SetValue(item, value);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM