LINQ表达式在哪里扩展 [英] LINQ Where expression to extend

查看:39
本文介绍了LINQ表达式在哪里扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何完成" LINQ到表达实体的实体.这就是我要写的:

I am wondering how to 'finish' a LINQ to Entities where expression. This is what I wanted to write:

IQueryable<Products> qry = ...
qry = ApplyFilter(qry, p => p.Name, "hello");

private IQueryable<Products> ApplyFilter(
          IQueryable<Products> qry, 
          Expression<Func<Products,String>> field, 
          String likeFilter)
{
  // ???
  return qry.Where( field.Contains( likeFilter )); 
}

调用语法很重要(需要简洁),函数参数和函数主体是弱点. :(我在lambda函数和表达式上越来越好,但目前还不够好:(感谢所有帮助和建议!

The call syntax is important (needs to be simple and clean), the function arguments and the function body is the weak point. :( I am getting better in lambda functions and expressions, but not enough good at this time :( Thanks for all the help and advices!

推荐答案

如果将方法设计为通用扩展方法(如其他linq扩展),效果会更好.

It will look better if you design your method as an generic extension method (like the other linq extensions).

public static class Extensions
{
    public static IQueryable<T> ApplyFilter<T>(this IQueryable<T> qry, Func<T, string> field, string likeFilter)
    {
        return qry.Where(x => field(x).Contains(likeFilter));
    }
}

用法:

IQueryable<Product> qry = new List<Product>() 
    { 
        new Product() {Name = "Ball", Category = "Sport"},
        new Product() {Name = "Bag", Category = "Other"},
        new Product() {Name = "Sport bag", Category = "Sport"},
    }.AsQueryable();

var result = qry.ApplyFilter(p => p.Category, "Sport");

此外,您可以将caseSensitive标志变量添加到扩展名方法中.

Additional you can add caseSensitive flag variable to your extension mehtod.

编辑- 试试这个修改:

public static IEnumerable<T> ApplyFilter<T>(this IQueryable<T> qry, Func<T, string> field, string likeFilter)
{
    foreach (var item in qry)
    {
        if (field(item).Contains(likeFilter))
        {
            yield return item;
        }
    }
}

不幸的是,我无法意识到这是否打破了IQueryable子句的累积.

Unfortunetly atm I can't realize if this broke the IQueryable clauses accumulation.

编辑2

好吧,我最终决定实现为构建表达式树,因此我可以确保将其成功转换为SQL.最终的(我希望是:D)解决方案:

Ok finnaly I decided to implement as building expression tree so I can be sure it'll be translated to SQL successful. The final (I hope :D) solution:

public static IQueryable<T> ApplyFilter<T>(this IQueryable<T> qry, Expression<Func<T, string>> field, string likeFilter)
{
    var member = field.Body as MemberExpression;
    var propInfo = member.Member as PropertyInfo;

    var param = Expression.Parameter(typeof(T), "x");
    var prop = Expression.Property(param, propInfo);

    var containsMethod = typeof(string).GetMethod("Contains");
    var body = Expression.Call(prop, containsMethod, Expression.Constant(likeFilter));
    var expr = Expression.Lambda<Func<T, bool>>(body, param);

    return qry.Where(expr);
}

这篇关于LINQ表达式在哪里扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆