2013-10-31 87 views
0

我正在使用linq表达式树(http://msdn.microsoft.com/en-us/library/vstudio/bb397951.aspx)创建复杂的动态创建的自定义过滤器。 现在我需要创建一个表达式,它不比较我表的属性,但是我的拆分属性的每个部分都有 。表达式树来拆分属性值

相应的静态LINQ的语句应该是:

myContext.MyEntityCollection 
.Where(item => item.MyProperty != null) 
.AsEnumerable<MyEntity>() 
.Select(item => item.MyProperty.Split(new[] { ',' }) 
.Where(.. my filter ..) 

例如在此输入上

Table MyEntity 
Id   MyProperty 
----------------------------------- 
1   part1,part2,part3,part4 
2   part5,part6 

我想搜索“part3”并获取第一行。

如何为分割func创建lambda表达式<>?

UPDATE:这是我到目前为止的状态(在我被卡住的最后一行)。另外我试图用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); 
+1

'.FirstOrDefault(p => p.Contains(“part3”));' – Sam

+0

@Rune FS:你为什么改变标题?我不感兴趣得到linq查询。这很简单。我需要真正的linq表达式语句。 – StefanG

+0

什么是“linq表达式语句”? :| – BartoszKP

回答

0

多次尝试之后,我认为这是不可能的表达式树做。 我最终做的是改变我的数据模型。

UPDATE由于一周内没有新的输入,我将其设置为答案。

0
.Where(t => t.Any(i => i=="part3")) 
+0

有关如何以及为什么您的答案可以工作的一点说明会很好。现在它只是一段代码。 – VDWWD

-1

为了获得该项目符合指定条件的使用:

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>() 
    .Where(item => item.MyProperty.Contains("part3")); 

或者,如果你因为某种原因需要使用Split

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); 
-1

我想这是你想要什么:

myContext.MyEntityCollection 
    .Where(item => item.MyProperty != null) 
    .AsEnumerable<MyEntity>() 
    .Where(item => item.MyProperty.Split(new [] { ',' }).Any(p => p == "part3"));