I have a database table that has 100 columns, labeled D1,D2,D3 and so on out to 100.
In my method (ASP.NET MVC) I need to check if these columns are null, before displaying them in a table in my view. I really don't want to have to do this:
if(db.Datatable.Select(x=>x.D1).FirstOrDefault() != null)
{
//do code
}
if(db.Datatable.Select(x=>x.D2).FirstOrDefault() != null)
{
//do code
}
if(db.Datatable.Select(x=>x.D3).FirstOrDefault() != null)
{
//do code
}
That would be 100 if statements and just look horrible. So I started this code here:
for(int i = 1; i < 100; i++)
{
var dbField = "D" + i; //D1,D2,D3....
var currField = db.Datatable.Select(x => x.dbField).FirstOrDefault();
//here i would add the value (0 for null, 1 for data) to an array, which i would handle in the view
}
Except LINQ/C# does not like this. It obviously throws an error on dbField in the Select statement. You can't just set .Select(x=x.variable). I have read on creating your own lambda expression tree and building a custom dynamic query, any thoughts on how to do this? How can I custom create the field name for the Select statement? Thank you.