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

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

问题描述

所以,我只是得到了一个建议,从亚马逊 LINQ到对象使用C#4.0:使用和扩展的LINQ to Objects和并行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和集成员访问检索或在底层的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天全站免登陆