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

前端 未结 3 1318
青春惊慌失措
青春惊慌失措 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:24

    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 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 GetDynamicMemberNames()
        {   
            return _row.Table.Columns.Cast().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.

提交回复
热议问题