As the question suggests I want to remove all of the columns from a LINQ query where all the rows in that column are empty.
At the minute I am using LINQ to run my initial query with the required date and site filters, this then returns an IEnumerable object to my ObjectDataSource within a GridView. This all works fine.
But I am having difficulties implementing the code to remove the empty / NULL columns (LINQ is very new to me).
Here is my working code to return the IEnumerable to the ObjectDataSource:
public IEnumerable<WebApplication1.HL_Log> Select(string startDate, string endDate)
{
DateTime start = DateTime.Now.AddDays(-1);
DateTime end = DateTime.Now;
if (startDate != "01/01/1900")
{
DateTime.TryParse(startDate, out start);
}
if (endDate != "01/01/1900")
{
DateTime.TryParse(endDate, out end);
}
DataClasses1DataContext db = new DataClasses1DataContext();
var query = from h in db.HL_Logs
where h.ID_Location == 45
&& h.Time_Stamp >= start.Date
&& h.Time_Stamp <= end.Date.AddDays(1)
orderby h.Time_Stamp
select h;
return query;
}
And so far I have been able to convert the result to a datatable and remove the null columns as I have done in other projects with a datatable using the below:
//Convert to a Datatable
DataTable dt = new DataTable();
dt = LINQToDataTable(query);
//Now remove the completely NULL columns
foreach(var column in dt.Columns.Cast<DataColumn>().ToArray())
{
if (dt.AsEnumerable().All(dr => dr.IsNull(column)))
dt.Columns.Remove(column);
}
But I need to then convert this back to IEnumerable before I can return it to my ObjectDataSource. So really my qustion is either, how do I convert the datatable back to an IEnumerable or am I using a very inefficent approch to this, if so what would be the best way to achieve my result??
My Overall code so far for this::
public IEnumerable<WebApplication1.HL_Log> Select(string startDate, string endDate)
{
DateTime start = DateTime.Now.AddDays(-1);
DateTime end = DateTime.Now;
if (startDate != "01/01/1900")
{
DateTime.TryParse(startDate, out start);
}
if (endDate != "01/01/1900")
{
DateTime.TryParse(endDate, out end);
}
DataClasses1DataContext db = new DataClasses1DataContext();
var query = from h in db.HL_Logs
where h.ID_Location == 45
&& h.Time_Stamp >= start.Date
&& h.Time_Stamp <= end.Date.AddDays(1)
orderby h.Time_Stamp
select h;
//Convert to a Datatable
DataTable dt = new DataTable();
dt = LINQToDataTable(query);
//Now remove the completely NULL columns
foreach(var column in dt.Columns.Cast<DataColumn>().ToArray())
{
if (dt.AsEnumerable().All(dr => dr.IsNull(column)))
dt.Columns.Remove(column);
}
//return ""HELP"";
}
Thanks for your help!!