LINQ Dynamically Select Column From Column Name
11,460
Solution 1
From what you are trying to achieve with reflection, below code should work:
var ss = liDeatil.Select(s => new MyClass{ Id = s.Id ,
Marks = (string)s.GetType().GetProperty("ColumnMarks").GetValue(s,null)}).Tolist();
Solution 2
What isn't working exactly? Are you getting an exception? I'm confused where you are getting "ColumnMarks" from. You didn't post the definition for MyTable, so maybe it is from there.
liDeatil.Select(s => new myclass{ Id = s.Id, Marks = (string)s.GetType().GetProperty("ColumnMarks").GetValue(s, null)}).Tolist();
Author by
Amit Bisht
MyExperience Ex; foreach(Day day in MyLife) { Ex = new Experiences(); day.Add(Ex); }
Updated on June 13, 2022Comments
-
Amit Bisht almost 2 years
I made this query to get data from a table
List<MyTable> liDeatil = Db.Database.SqlQuery<MyTable>("SELECT * FROM [myDB].[dbo].[MyTable]").ToList();
From
liDetail
i want to select column dynamically such asliDeatil.Select(s => new myclass{ Id = s.Id ,Marks = ....}).Tolist();
Where MyClass is
public class MyClass { public Nullable<decimal> Id { get; set; } public string Marks { get; set; } public string rank { get; set; } }
is there any way to get the column pls help me
I tried To do this by reflection But its not workingvar ss = liDeatil.Select(s => new MyClass{ Id = s.Id ,Marks = s.GetType().GetProperties("ColumnMarks")}).Tolist();
EDITED
public class MyTable { public Nullable<decimal> Id { get; set; } public string ColumnMarks{ get; set; } public string ColumnMarks1{ get; set; } public string ColumnMarks2{ get; set; } }
-
Amit Bisht over 10 yearsi HAD EDITED MY QUESTION
-
Dude0001 over 10 yearsThis answer or Victor's below should work then. You need to call GetValue once you get the property via reflection.
-
Victor Mukherjee over 10 yearsI have edited my code, try with "GetProperty("ColumnMarks")" instead of "GetProperties("ColumnMarks")"