通用LINQ查询predicate? [英] Generic LINQ query predicate?
问题描述
不知道这是可能的,或者如果我的前pressing我正在寻找正确的东西,但我有下面这段code在我的图书馆反复想练习一些干。 我已经设置基于ALA谷歌一个简单的用户提供的搜索字段,我查询的SQL Server表。我使用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搜索和字段名搜索。这是否有意义?有没有使用LINQ的方式来动态传递领域的where子句中查询这个名字?或者,我可以通过在此为predicate拉姆达?
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?
推荐答案
这听起来像你正在寻找动态的LINQ。看看<一href="http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx"相对=nofollow>此处。这使您可以传递字符串作为参数的查询方法,如:
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部分。
这篇关于通用LINQ查询predicate?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!