开发者

Dynamic Linq to Datatable Derived Field

Is it possible to use Dynamic Linq to run a query similar to:

Select a, b, a + b as c from MyDataTable

I have an application where the user can enter SQL statements, the results of these statements are then assigned to a DataTable. There is also the option to derive a field based on other fields. (e.g. user can say field C = a + b, or field D = A*B+10 etc).

Ideally I would like to do something similar 开发者_JS百科to:

string myCalc = "Convert.ToDouble(r.ItemArray[14])+Convert.ToDouble(r.ItemArray[45])";

var parameters = from r in dt.AsEnumerable() select (myCalc);

What I want to do in this example is add the value of column 14 to column 45 and return it. It's up to the user to decide what expression to use so the text in the select needs to be from a string, I cannot hard code the expression. The string myCalc is purely for demonstration purposes.


You could do that using a Dictionary, and a DataReader and Dynamic Queries. Here is an example based in part in Rob Connery's Massive ORM RecordToExpando:

void Main()
{
    string connString = "your connection string";

    System.Data.SqlClient.SqlConnection conn = new SqlConnection(connString);
    string statement = "SUM = EstimatedEffort + OriginalEstimate, Original = OriginalEstimate";
    // Note: You should parse the statement so it doesn't have any updates or inserts in it.
    string sql = "SELECT " + statement +" FROM Activities";

    List<IDictionary<string, object>> results = new List<IDictionary<string, object>>();    
    conn.Open();

    using(conn)
    {
        var cmd = new SqlCommand(sql,  conn);
        var reader = cmd.ExecuteReader();
        while (reader.Read())
        {               
            var dic = new Dictionary<string, object>();
            for (int i = 0; i < reader.FieldCount; i++)
            {
                dic.Add(
                    reader.GetName(i), 
                    DBNull.Value.Equals(reader[i]) ? null : reader[i]);
            }

            results.Add(dic);           
        }
    }


    foreach (var dicRow in results)
    {       
        foreach (string key in dicRow.Keys)
        {
            Console.Write("Key: " + key + " Value: " + dicRow[key]);
        }

        Console.WriteLine();
    }   
}


Something like this:

void Main()
{
    var dataTable = new DataTable();
    dataTable.Columns.Add("a", typeof(double));
    dataTable.Columns.Add("b", typeof(double));

    dataTable.Rows.Add(new object[] { 10, 20 });
    dataTable.Rows.Add(new object[] { 30, 40 });

    string myCalc = "Convert.ToDouble(ItemArray[0]) + Convert.ToDouble(ItemArray[1])";

    var query = dataTable.AsEnumerable().AsQueryable();
    var result = query.Select(myCalc);

    foreach (Double c in result)
    {
        System.Console.WriteLine(c);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜