Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/elixir/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何创建动态where子句?_C#_Linq_Dynamic Linq - Fatal编程技术网

C# 如何创建动态where子句?

C# 如何创建动态where子句?,c#,linq,dynamic-linq,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 != "

在下面的代码中

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);
CLUSE是一个字符串,它包含
“languageId=@0,categoryid=@1”

其中value也是一个字符串,它包含
“1,1”


我需要去掉那些引号。我该怎么做呢?

在library的帮助下,可以做到这一点,简单到:

var result = context.vCatalogItemsDetails
                    .Where(cluase, whereValue) 
                    .Where("landuageID=1 AND categoryid=1")
                    .OrderBy("itemID")
                    .Skip((pageN - 1) * 10).Take(10);
对于这种“动态”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;
}
公共静态IEnumerable筛选器(此IEnumerable源,
字符串名,字符串名)
{
if(firstname!=null)
{
来源=来源中的个人
其中person.Firstname.Contains(Firstname)
选择人员;
}
if(lastname!=null)
{
来源=来源中的个人
其中person.Lastname.Contains(Lastname)
选择人员;
}
返回源;
}

同样的技术也适用于
IQueryable

这里有一篇关于CodeProject的好文章:。