Hub*_*pek 1 c# linq lambda expression linq-expressions
我有一个Linq表达式列表,List<Expression>其中每个表达式类型(表达式将返回的类型)是Item或Item[].
我正在尝试编写一些代码,将提到的集合作为输入参数,并生成一个Linq表达式,它将返回一个列表(或数组)的项目(Item[]).
这是一个抽象的例子:
public static string[] GetStrings()
{
return new[]
{
"first",
"second",
"third"
};
}
public static string GetString()
{
return "single1";
}
private void SOExample()
{
var expressions = new List<Expression>
{
Expression.Call(GetType().GetMethod("GetString")),
Expression.Call(GetType().GetMethod("GetStrings")),
Expression.Call(GetType().GetMethod("GetString")),
Expression.Call(GetType().GetMethod("GetStrings"))
};
// some magic code here
var combined = SomeMagicHere(expressions);
}
private Expression SomeMagicHere(List<Expression> expressions)
{
foreach (var expression in expressions)
{
if (expression.Type.IsArray)
{
// Use array's elements
}
else
{
// Use expression
}
}
Run Code Online (Sandbox Code Playgroud)
我想要做的是生成一个表达式,它将Item从提供的列表中返回(我的例子中的字符串)列表.
这似乎是一个非常奇怪的场景,在大多数情况下,我希望看到使用原始反射(或者代表)而不是Expression在这里 - 它不是一个明显的选择.但是:您可以通过将表达式转换为每个调用的块Add或AddRange将值附加到列表中来实现.例如:
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
static class Program
{
public static string GetString()
{
return "single1";
}
public static string[] GetStrings()
{
return new[]
{
"first",
"second",
"third"
};
}
static void Main()
{
var expressions = new List<Expression>
{
Expression.Call(typeof(Program).GetMethod("GetString")),
Expression.Call(typeof(Program).GetMethod("GetStrings")),
Expression.Call(typeof(Program).GetMethod("GetString")),
Expression.Call(typeof(Program).GetMethod("GetStrings"))
};
// some magic code here
var combined = SomeMagicHere(expressions);
// show it works
var lambda = Expression.Lambda<Func<List<string>>>(combined);
var list = lambda.Compile()();
}
private static Expression SomeMagicHere(List<Expression> expressions)
{
List<Expression> blockContents = new List<Expression>();
var var = Expression.Variable(typeof(List<string>), "list");
blockContents.Add(Expression.Assign(var,
Expression.New(typeof(List<string>))));
foreach (var expression in expressions)
{
if (expression.Type.IsArray)
{
blockContents.Add(Expression.Call(
var, var.Type.GetMethod("AddRange"), expression));
}
else
{
blockContents.Add(Expression.Call(var,
var.Type.GetMethod("Add"), expression));
}
}
blockContents.Add(var); // last statement in a block is the effective
// value of the block
return Expression.Block(new[] {var}, blockContents);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1292 次 |
| 最近记录: |