开发者

linq to entities, operator like WhereAnyIn?

I saw whereIn开发者_如何学JAVA implementation before. But I'm wondering can someone show me to write a opration "WhereAnyIn".

for example: Ive an entities: Post --- PostTag --- Tag

I need a query with parameter int[] tagids, which where fetch all posts that has any of tagid in the given list.

I cannot figure it out .

thanks for your help.


    static void Main(string[] args)
    {
        int[] integers = Enumerable.Range(0, 10).ToArray();
        Expression<Func<Post, bool>> expression = CreateWhereInExpression<Post, int>(p => p.Tag, integers);
    }

    static Expression<Func<TItem, bool>> CreateWhereInExpression<TItem, TValue>(Expression<Func<TItem, TValue>> lambda, TValue[] items)
    {
        if (lambda != null)
        {
            MemberExpression memberExpression = lambda.Body as MemberExpression;
            if (memberExpression != null && memberExpression.Expression == lambda.Parameters[0])
            {
                Expression body;
                if (items == null || items.Length == 0)
                {
                    body = Expression.Constant(
                        true
                    );
                }
                else
                {
                    body = items.Skip(1).Aggregate(
                        Expression.Equal(
                            memberExpression,
                            Expression.Constant(items[0])
                        ),
                        (expression, item) => Expression.OrElse(
                            expression,
                            Expression.Equal(
                                memberExpression,
                                Expression.Constant(
                                    item
                                )
                            )
                        )
                    );
                }
                return Expression.Lambda<Func<TItem, bool>>(
                    body,
                    lambda.Parameters
                );
            }
        }
        return null;
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜