Selecting Columns in LINQ using System.Linq.Expres

2019-05-15 02:17发布

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.

2条回答
做自己的国王
2楼-- · 2019-05-15 02:56
 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#

查看更多
Explosion°爆炸
3楼-- · 2019-05-15 03:19

In C# it would look like this

var myStringLengths = myStrings
                        .Select((s) => s.Length);
查看更多
登录 后发表回答