如何转换此Func<;SampleExpression,IEnumerator<;字符串>;,bool>
本文关键字:lt gt SampleExpression 字符串 bool IEnumerator 转换 Func 何转换 | 更新日期: 2023-09-27 18:29:48
这是我的类
class SampleExpression
{
public string str;
public static bool SampleEnum(SampleExpression s, IEnumerator<string> ien = null)
{
while (ien.MoveNext())
{
if (s.str == ien.Current)
{
ien.Reset();
return true;
}
}
return false;
}
}
这就是我在运行时生成表达式树的方式:
static void Main(string[] args)
{
ParameterExpression param1 = Expression.Parameter(typeof(SampleExpression), "token");
ParameterExpression param2 = Expression.Parameter(typeof(IEnumerator<string>), "args");
var lstConstant = "1,2,3,4,".Split(new string[] { "," },
StringSplitOptions.RemoveEmptyEntries).ToList();
var enummethod = typeof(SampleExpression).GetMethod("SampleEnum");
MethodCallExpression methodCall = Expression.Call
(
enummethod,
param1
, param2
);
var e = Expression.Lambda<Func<SampleExpression, IEnumerator<string>, bool>>(methodCall, param1, param2);
var l = e.Compile();
List<SampleExpression> lst = new List<SampleExpression>();
lst.Add(new SampleExpression { str = "1" }); // matches with lstConstant
lst.Add(new SampleExpression { str = "2" }); // matches with lstConstant
lst.Add(new SampleExpression { str = "5" });
var items = lst.Where(x => l(x, lstConstant.GetEnumerator())).ToList();
}
现在我可能已经以一种复杂的方式完成了这项工作(因为我是表达式树的新手)——我的要求是:
我有一个逗号分隔的字符串,如"1,2,3,4,"
。我想将每个SampleExpression
与类SampleExpression
的字符串参数str
进行拆分和匹配。到目前为止我已经做到了。
但是,我希望表达式为Func<SampleExpression,bool>
。正如您目前看到的Func<SampleExpression, IEnumerator<string>, bool>
。
我该怎么解决这个问题。
表达式编译对我来说也很奇怪,但要真正回答你的问题。。。
你可以这样包装编译后的Func:
Func<SampleExpression, bool> lBind = (SampleExpression token) => l(token, lstConstant.GetEnumerator());
这将枚举器绑定为第二个参数,同时保留第一个参数以供输入。
我不清楚你为什么要进行动态表达式编译,所以我只关注你的问题陈述:
我有一个逗号分隔的字符串,如
"1,2,3,4,"
。我想将每个SampleExpression
与类SampleExpression
的字符串参数str
进行拆分和匹配。
LINQ实际上提供了一种非常简单的方法来处理这个问题:
var lstConstant = "1,2,3,4,".Split(new string[] { "," },
StringSplitOptions.RemoveEmptyEntries).ToList();
List<SampleExpression> lst = new List<SampleExpression>();
lst.Add(new SampleExpression { str = "1" }); // matches with lstConstant
lst.Add(new SampleExpression { str = "2" }); // matches with lstConstant
lst.Add(new SampleExpression { str = "5" });
var items = lst.Where(x => lstConstant.Contains(x.str)).ToList();
如果您想让这个逻辑驻留在SampleExpression
类中,那很好:
class SampleExpression
{
public string str;
public static bool SampleEnum(SampleExpression s, IEnumerable<string> ien)
{
return ien.Contains(s.str);
}
}
// Usage:
var items = lst.Where(x => SampleExpression.SampleEnum(x, lstConstant))
.ToList();
如果希望SampleEnum
方法本身返回要传递到Where
子句中的值,则可以执行以下操作:
class SampleExpression
{
public string str;
public static Func<SampleExpression, bool> SampleEnum(IEnumerable<string> ien)
{
return s => ien.Contains(s.str);
}
}
// Usage:
var items = lst.Where(SampleExpression.SampleEnum(lstConstant))
.ToList();