I want to use Linq to dynamically select DataTable columns by ColumnName but to use Field<> I must explicitly cast them or box everything to an object, which is not efficient.
I tried:
string[] colsNames = new[] { "Colum1", "Colum2" };
DataTable dt = StoredProcedure().Tables[0];
var cols = dt.Columns.Cast<DataColumn>().Where(c => cols.Contains(c.ColumnName));
if (cols.Any())
{
dt.AsEnumerable().Select(r => string.Join(":", cols.Select(c => r.Field<c.DataType>(c.ColumnName))))
}
but this throws me an error The type or namespace name 'c' could not be found
How do I convert typeof(decimal)
to Field<decimal>("Column1")
for example?
Try this:
Here is another variant, but it is not very interesting:
There is a third variant: you can create a view or stored procedure in the database and add it to the data context