Nice examples of using .NET 4 dynamic keyword with Linq?

前端 未结 3 1304
青春惊慌失措
青春惊慌失措 2021-02-01 06:47

So I Just got a recommendation from Amazon for LINQ to Objects Using C# 4.0: Using and Extending LINQ to Objects and Parallel LINQ (PLINQ).

It says that the book introdu

3条回答
  •  甜味超标
    2021-02-01 07:17

    Joe's answer is cool. I have an idea how to simplify the usage. If you add this to the extension class:

    public static class Extensions
    {    
    
        public static IEnumerable ExecuteSql(this UserQuery uq, string sql)
        {
            var connStr="Provider=SQLOLEDB.1;"+uq.Connection.ConnectionString; 
    
            OleDbConnection connection = new OleDbConnection(connStr);
            DataSet myDataSet = new DataSet();
            connection.Open();
    
            OleDbDataAdapter DBAdapter = new OleDbDataAdapter();
            DBAdapter.SelectCommand = new OleDbCommand(sql, connection); 
            DBAdapter.Fill(myDataSet);
    
            var result = myDataSet.Tables[0].AsDynamic();
            return result;
        }
    }
    

    It allows to use queries like this in LINQPad:

    void Main()
    {
        var query1 = from cust in this.ExecuteSql("SELECT * from Customers")
            where cust.ContactName.StartsWith ("C")
            orderby cust.ContactName
            select new { cust.CustomerID, cust.ContactName, cust.City };        
        query1.Dump();      
    }
    

    N.B.: You need to add the following references:

    • Add System.Data.OleDb from the System.Data assembly to the query properties
    • Add System.Dynamic to the query properties

    • uq.Connection is only available if you have associated a database via the Connection dropdown. If you have selected "", a compile error will occur.


    Update: I noticed that Joe has added a function ExecuteQueryDynamic in the latest Beta v4.53.03 of LinqPad, which can be used to achieve this, for example:

    void Main()
    {
        var q=this.ExecuteQueryDynamic("select * from Customers");
        q.Dump();
    }
    

    This will return the Customers table from the Northwind database as IEnumerable, using a Linq2Sql connection.

提交回复
热议问题