使用.NET 4动态关键字和Linq的很好的例子? [英] Nice examples of using .NET 4 dynamic keyword with Linq?

查看:182
本文介绍了使用.NET 4动态关键字和Linq的很好的例子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我只是从亚马逊推荐了一个 LINQ to Objects Using C#4.0:Using and将LINQ扩展到对象和并行LINQ(PLINQ)

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).

它说这本书使用动态关键字与Linq,这让我想到:

It says that the book introduces using the dynamic keyword with Linq, which got me thinking:

你可以用动态关键字做什么样的事情那么你不能用Linq来做另外一个事情呢?

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

推荐答案

这是一个想法:通过结合LINQ和动态,你可以查询非类型数据集好像他们是打字的。

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

例如,假设myDataSet是一个无类型的DataSet。使用动态打字和一个名为AsDynamic()的扩展方法,可以执行以下操作:

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 };

以下是定义AsDynamic扩展方法的方法。注意它如何返回IEnumerable的动态,这使它适合LINQ查询:

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);
    }
  }
}

通过子类化DynamicObject,自定义绑定的优势 - 您自己处理会员名称的过程。在这种情况下,我们将get和set成员访问绑定到基础DataRow中的检索或存储对象。

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.

这篇关于使用.NET 4动态关键字和Linq的很好的例子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆