C# 要拆分属性值的表达式树
我正在使用linq表达式树来创建复杂的、动态创建的自定义过滤器。 现在我需要创建一个表达式,它不是比较表的属性,而是比较 我分割财产的每一部分 相应的静态linq语句为:C# 要拆分属性值的表达式树,c#,linq,expression-trees,C#,Linq,Expression Trees,我正在使用linq表达式树来创建复杂的、动态创建的自定义过滤器。 现在我需要创建一个表达式,它不是比较表的属性,而是比较 我分割财产的每一部分 相应的静态linq语句为: myContext.MyEntityCollection .Where(item => item.MyProperty != null) .AsEnumerable<MyEntity>() .Select(item => item.MyProperty.Split(new[] { ',' })
myContext.MyEntityCollection
.Where(item => item.MyProperty != null)
.AsEnumerable<MyEntity>()
.Select(item => item.MyProperty.Split(new[] { ',' })
.Where( .. my filter ..)
我想搜索part3并获得第一行
如何为split func创建lambda表达式
更新:这是我到目前为止在最后一行被卡住的状态。我还试图用ExpressionTreeViewer从上面的linq语句构建表达式树,但它不起作用,我想是因为.AsEnumerable
ParameterExpression param = Expression.Parameter(typeof(ReportIndex), "MyEntity");
MemberExpression stringProperty = Expression.Property(param, "MyProperty");
MethodInfo mi = typeof(string).GetMethod("Split", new[] { typeof(char[]) });
MethodCallExpression splitExpression =
Expression.Call(exDateProperty, mi, Expression.Constant(new[] { '|' }));
MethodInfo containsMethod = typeof(ICollection<string>).GetMethod("Contains");
var expression = Expression.Call(param, containsMethod, splitExpression, stringProperty);
要获取与给定条件匹配的项目,请使用:
var rows = myContext.MyEntityCollection
.Where(item => item.MyProperty != null)
.AsEnumerable<MyEntity>()
.FirstOrDefault(item => item.MyProperty.Contains("part3"));
更清晰的版本:
var rows = myContext.MyEntityCollection
.Where(item => item.MyProperty != null)
.AsEnumerable<MyEntity>()
.Select(item => new
{
Item = item,
Parts = item.MyProperty.Split(new[] { ',' })
})
.Where(itemWithParts => itemWithParts.Parts.Contains("part3"))
.Select(itemWithParts => itemWithParts.Item);
我想这就是你想要的:
myContext.MyEntityCollection
.Where(item => item.MyProperty != null)
.AsEnumerable<MyEntity>()
.Where(item => item.MyProperty.Split(new [] { ',' }).Any(p => p == "part3"));
经过多次尝试,我认为不可能使用表达式树。 我最终做的是改变我的数据模型
更新由于一周内没有新的输入,我将其设置为应答。.FirstOrDefaultp=>p.containsARPT3@符文FS:你为什么改变标题?我对获取linq查询不感兴趣。这很简单。我需要linq表达式语句。什么是linq表达式语句|你要找的不是表达式树。表达式树是语句的计算表示形式。也就是说,当您使用代码动态构建代码时,我指的是可以用作linq提供程序的表达式树。请看一个关于你的答案如何以及为什么会起作用的小解释。现在它只是一段代码。
var rows = myContext.MyEntityCollection
.Where(item => item.MyProperty != null)
.AsEnumerable<MyEntity>()
.Where(item => item.MyProperty.Contains("part3"));
var rows = myContext.MyEntityCollection
.Where(item => item.MyProperty != null)
.AsEnumerable<MyEntity>()
.Where(item => item.MyProperty.Split(new[] { ',' }).Contains("part3"));
var rows = myContext.MyEntityCollection
.Where(item => item.MyProperty != null)
.AsEnumerable<MyEntity>()
.Select(item => new
{
Item = item,
Parts = item.MyProperty.Split(new[] { ',' })
})
.Where(itemWithParts => itemWithParts.Parts.Contains("part3"))
.Select(itemWithParts => itemWithParts.Item);
myContext.MyEntityCollection
.Where(item => item.MyProperty != null)
.AsEnumerable<MyEntity>()
.Where(item => item.MyProperty.Split(new [] { ',' }).Any(p => p == "part3"));