通用 LINQ 查询谓词? [英] Generic LINQ query predicate?

查看:16
本文介绍了通用 LINQ 查询谓词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不确定这是否可行,或者我是否正确表达了我正在寻找的内容,但是我的库中反复出现以下代码片段,并且想练习一些 DRY.我有一组 SQL Server 表,我根据用户提供的简单搜索字段 ala Google 查询这些表.我正在使用 LINQ 根据搜索字符串中的内容编写最终查询.我正在寻找一种方法来使用泛型并传入 lambda 函数来创建一个可重用的例程:

Not sure if this is possible or if I'm expressing correctly what I'm looking for, but I have the following piece of code in my library repeatedly and would like to practice some DRY. I have set of SQL Server tables that I'm querying based on a simple user-supplied search field ala Google. I'm using LINQ to compose the final query based on what's in the search string. I'm looking for a way to use generics and passed in lambda functions to create a reusable routine out of this:

string[] arrayOfQueryTerms = getsTheArray();

var somequery = from q in dataContext.MyTable
                select q;

if (arrayOfQueryTerms.Length == 1)
{
    somequery = somequery.Where<MyTableEntity>(
        e => e.FieldName.StartsWith(arrayOfQueryTerms[0]));
}
else
{
    foreach(string queryTerm in arrayOfQueryTerms)
    {
        if (!String.IsNullOrEmpty(queryTerm))
        {
            somequery = somequery 
                        .Where<MyTableEntity>(
                            e => e.FieldName.Contains(queryTerm));
        }
    }
}

我希望创建一个带有类似于以下签名的通用方法:

I was hoping to create a generic method with signature that looks something like:

private IQueryable<T> getQuery(
    T MyTableEntity, string[] arrayOfQueryTerms, Func<T, bool> predicate)

我在我的所有表中使用相同的搜索策略,所以唯一真正不同的是 MyTable &MyTableEntity 搜索和 FieldName 搜索.这有意义吗?LINQ 有没有办法动态传入字段的名称以在 where 子句中查询?或者我可以将其作为谓词 lambda 传入?

I'm using the same search strategy across all my tables, so the only thing that really differs from usage to usage is the MyTable & MyTableEntity searched and the FieldName searched. Does this make sense? Is there a way with LINQ to dynamically pass in the name of the field to query in the where clause? Or can I pass in this as a predicate lambda?

e => e.FieldName.Contains(queryTerm)

我意识到在 SQL 中有一百万种半的方法可以做到这一点,可能更容易,但我很想为这个保留 LINQ 系列中的所有内容.另外,我觉得泛型应该很方便解决这样的问题.有什么想法吗?

I realize there a million and a half ways to do this in SQL, probably easier, but I'd love to keep everything in the LINQ family for this one. Also, I feel that generics should be handy for a problem like this. Any ideas?

推荐答案

听起来您正在寻找 Dynamic Linq.看看 此处.这允许您将字符串作为参数传递给查询方法,例如:

It sounds like you're looking for Dynamic Linq. Take a look here. This allows you to pass strings as arguments to the query methods, like:

var query = dataSource.Where("CategoryID == 2 && UnitPrice > 3")
                      .OrderBy("SupplierID");

关于这个主题的另一组帖子,使用 C# 4 的动态支持:第 1 部分第 2 部分.

Another set of posts on this subject, using C# 4's Dynamic support: Part 1 and Part 2.

这篇关于通用 LINQ 查询谓词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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