Reversing typeof to use Linq Field

2019-09-09 17:53发布

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?

1条回答
Melony?
2楼-- · 2019-09-09 18:04

Try this:

DataTable dt = new DataTable();
dt.Columns.Add("id", Type.GetType("System.Int32"));
dt.Columns.Add("Colum1", Type.GetType("System.Int32"));
dt.Columns.Add("Colum2", Type.GetType("System.String"));
dt.Columns.Add("Colum3");

string[] colsNames = new[] { "Colum1", "Colum2" };
var colTypes = dt.Columns.Cast<DataColumn>()
                 .Where(c => colsNames.Contains(c.ColumnName))
                 .Select(c => new
                 {
                     c.ColumnName,
                     c.DataType
                 })
                 .ToDictionary(key => key.ColumnName, val => val.DataType);

var query = dt.AsEnumerable()
              .Where(row => (int)row["id"]==5)
              .Select(row => new
              {
                  Colum1 = Convert.ChangeType(row[colsNames[0]], colTypes[colsNames[0]]),
                  Colum2 = Convert.ChangeType(row[colsNames[1]], colTypes[colsNames[1]])
              });

Here is another variant, but it is not very interesting:

//define class
public class myClass
{
    public int Column1;
    public string Column2;
}
// then
var query = dt.AsEnumerable()
              .Select(row => new myClass
              {
                  Column1 = Convert.ToInt32(row[colsNames[0]]),
                  Column2 = row[colsNames[1]].ToString()
              });

There is a third variant: you can create a view or stored procedure in the database and add it to the data context

查看更多
登录 后发表回答