How to create a dynamic where clause?

c# dynamic-linq linq

Question

in this below code

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 is a string and it contains "languageId=@0, categoryid=@1"

whereValue is also a string and it contains "1,1"

i need to remove those quotation marks. how can i do it?

1
0
7/29/2014 6:56:44 AM

Popular Answer

For this kind of "dynamic" where clause, there is often no need to use expression based features. You just have to realize that multiple Where calls can be composed.

For example:

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;
}

The same technique works with IQueryable<T> too.

1
7/29/2014 7:15:18 AM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow