Get Column Dynamically in LINQ
-
If anyone is having idea regarding my below query please let me know. - I’ve one table with 3 column Price_GBP, Price_EUR, Price_USD. - I want to execute one LINQ query which can get column dynamically - For example, in one function, if I pass “Price_GBP” than same query should return value of price from Price_GBP column same for Euro & US Dollar.
Believe Yourself™
-
If anyone is having idea regarding my below query please let me know. - I’ve one table with 3 column Price_GBP, Price_EUR, Price_USD. - I want to execute one LINQ query which can get column dynamically - For example, in one function, if I pass “Price_GBP” than same query should return value of price from Price_GBP column same for Euro & US Dollar.
Believe Yourself™
Well here's a possible solution using reflection:
//a dummy class public class Price { public decimal Eur { get; set; } public decimal USD { get; set; } } //a dummy list List<Price> prices = new List<Price>(); private void button1\_Click(object sender, EventArgs e) { prices.Add(new Price { Eur = 3.2m, USD = 4.1m }); //option1 => use a separate method var result = (from rec in prices select GetValue(rec, "Eur")).First(); //option2 => inline it var result2 = (from rec in prices select rec.GetType().GetProperty("USD").GetValue(rec, null)).First(); MessageBox.Show(result.ToString()); MessageBox.Show(Convert.ToDecimal(result2).ToString()); } private decimal GetValue(Price pr, string propName) { return (decimal)pr.GetType().GetProperty(propName).GetValue(pr, null); } }
Of course the "EUR" or "USD" will be a method param or something, not hard coded as in this example. Hope It helps.