Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 introduces using the dynamic keyword with Linq, which got me thinking:

What kind of awesomeness could you do with the dynamic keyword that you couldn't do with Linq otherwise?

like image 997
Rei Miyasaka Avatar asked Nov 07 '10 12:11

Rei Miyasaka


1 Answers

Here's an idea: by combining LINQ with dynamic, you can query untyped datasets as though they were typed.

For instance, suppose that myDataSet is an untyped DataSet. With dynamic typing and an extension method called AsDynamic(), the following is possible:

var query = from cust in myDataSet.Tables[0].AsDynamic()
  where cust.LastName.StartsWith ("A")
  orderby cust.LastName, cust.FirstName
  select new { cust.ID, cust.LastName, cust.FirstName, cust.BirthDate };

Here's how to define the AsDynamic extension method. Notice how it returns IEnumerable of dynamic, which makes it suitable for LINQ queries:

public static class Extensions
{    
  public static IEnumerable<dynamic> AsDynamic (this DataTable dt)
  {
    foreach (DataRow row in dt.Rows) yield return row.AsDynamic();
  }

  public static dynamic AsDynamic (this DataRow row)
  {
    return new DynamicDataRow (row);
  }

  class DynamicDataRow : DynamicObject
  {
    DataRow _row;
    public DynamicDataRow (DataRow row) { _row = row; }

    public override bool TryGetMember (GetMemberBinder binder, out object result)
    {
      result = _row[binder.Name];
      return true;
    }

    public override bool TrySetMember (SetMemberBinder binder, object value)
    {
      _row[binder.Name] = value;
      return true;
    }

    public override IEnumerable<string> GetDynamicMemberNames()
    {   
        return _row.Table.Columns.Cast<DataColumn>().Select (dc => dc.ColumnName);
    }
  }
}

By subclassing DynamicObject, this takes advantage of custom binding - where you take over the process of resolving member names yourself. In this case, we bind the get and set member access to retrieving or storing objects in the underlying DataRow.

like image 147
Joe Albahari Avatar answered Oct 14 '22 05:10

Joe Albahari