使用选择列在LINQ System.Linq.Ex pressions API [英] Selecting Columns in LINQ using System.Linq.Expressions API

查看:174
本文介绍了使用选择列在LINQ System.Linq.Ex pressions API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用LINQ EX pressions动态地选择列从的IEnumerable 到结果集,我可以绑定到我的用户界面。在这一点上我有一个困难时期刚刚抓投影的基本知识,在LINQ EX pressions。

让我们说我有一个字符串列表,就像这样:

 暗淡myStrings = {一,二,三}了ToList()
 

使用lambda EX pressions我可以轻松地做选择出的字符串长度的集合:

 暗淡myStringLengths = myStrings.Select(功能(X)x.Length)
 

该语句的结果会离开我有一个名为集 myStringLengths 有元素 3,3,5

我似乎无法弄清楚是如何可以使用LINQ EX pression产生同样的结果。

编辑::当我说的LINQ EX pression,我说的是使用API​​中的 System.Linq.Ex pressions 命名空间的LINQ说明书或lambda EX pression不是标准形式。正如你可以清楚地看到上面的,我已经熟悉如何生成一个投影的方式。

任何帮助是极大的AP preciated。

解决方案

  VAR项=前pression.Parameter(typeof运算(字符串),X);
 VAR长度=前pression.PropertyOrField(项目,长度);

 新的String [] {一,二,三}
      .AsQueryable()
      。选择(前pression.Lambda< Func键<字符串,INT>>(长,项目));
 

您需要一个IQueryable使用EX pressions(你可以把它带回了IEnumerable用了ToList或similiar)。 然后你产生拉姆达为前pression树(长度例如上面完成)。 对不起它在C#

I'm trying to use LINQ expressions to dynamically select columns from an IEnumerable into a result set that I can bind to my UI. At this point I am having a hard time just grasping the basics of projection in LINQ expressions.

Let's say I have a list of strings like so:

Dim myStrings = {"one", "two", "three"}.ToList()

Using lambda expressions I can easily select out a collection of string lengths by doing:

Dim myStringLengths = myStrings.Select(Function(x) x.Length)

The result of this statement would leave me with a collection called myStringLengths that have the elements 3, 3, 5.

What I can't seem to figure out is how I can produce the equivalent result using a LINQ expression.

Edit: When I say LINQ expression, I am talking about using the API in the System.Linq.Expressions namespace, not the standard form of a LINQ statment or lambda expression. As you can clearly see above, I am already familiar with how to generate a projection that way.

Any help is greatly appreciated.

解决方案

 var item = Expression.Parameter(typeof(string), "x");
 var length = Expression.PropertyOrField(item, "Length");

 new string[] {"one", "two", "three"}
      .AsQueryable()
      .Select(Expression.Lambda<Func<string, int>>(length, item));

You need an IQueryable to use expressions (you can bring it back to IEnumerable with ToList or similiar). Then you generate the Lambda as an expression tree (the length example is done above). Sorry its in C#

这篇关于使用选择列在LINQ System.Linq.Ex pressions API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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