如何创建动态where子句?

时间:2014-07-29 06:54:59

标签: c# linq dynamic-linq

在下面的代码中

string cluase = string.Empty;
string whereValue = string.Empty;

foreach (var i in whereCluaseItems)
{
    if (cluase != "")
    {
        cluase += " and " + i.Name;
    }
    else
    {
        cluase = i.Name;
    }
    if (whereValue != "")
    {
        whereValue += "," + i.Value;
    }
    else
    {
        whereValue = i.Value;
    }
}

var result = context.vCatalogItemsDetails
                    .Where(cluase, whereValue) 
// since where syntax has to be like this : where("@landuageID=@0,categoryid=@1", 1,1)
.OrderBy("itemID")
.Skip((pageN - 1) * 10).Take(10);

cluase是一个字符串,它包含 "languageId=@0, categoryid=@1"

whereValue也是一个字符串,它包含 "1,1"

我需要删除那些引号。我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

对于这种"动态" where子句,通常不需要使用基于表达式的功能。您只需要意识到可以组成多个Where调用。

例如:

public static IEnumerable<Person> Filter(this IEnumerable<Person> source, 
    string firstname, string lastname)
{
    if (firstname != null)
    {
        source = from person in source
                 where person.Firstname.Contains(firstname)
                 select person;
    }

    if (lastname != null)
    {
        source = from person in source
                 where person.Lastname.Contains(lastname)
                 select person;
    }

    return source;
}

同样的技术也适用于IQueryable<T>

答案 1 :(得分:0)

Dynamic LINQ库的帮助下可以做到这一点,就像这样简单:

var result = context.vCatalogItemsDetails
                    .Where(cluase, whereValue) 
                    .Where("landuageID=1 AND categoryid=1")
                    .OrderBy("itemID")
                    .Skip((pageN - 1) * 10).Take(10);