Dynamically select and update a column value in a LINQ result set

I have a script in which a LINQ result set exists; I used the following query

var stockDetails = from d in db.BloodBanks
                   where d.bbUserName == Session["username"].ToString()
                   select d;

Now I want to use this result set and update the column value. A column is dynamically selected using a string variable.

The code I'm trying to use is:

foreach (BloodBank b in stockDetails)
            {
                b.<--column name from string variable--> = TextBox1.Text;
            }

Please help me find out how I can achieve this.

+3
source share
2 answers

You can use reflection to get a field by name like this.

foreach (BloodBank b in stockDetails)
{
    FieldInfo f = typeof(BloodBank).GetField("fieldName");
    if (f != null)
    {
       f.SetValue(b, TextBox1.Text);
    }
}
+3
source
foreach (BloodBank b in db.BloodBanks.Where(d => where d.bbUserName == Session["username"].ToString())
{
    b.col = TextBox1.Text;
}
+1
source

All Articles