简体   繁体   中英

LINQ - Where Clause using Contains

I have a LINQ statement that I need to do a "contains" with, but also need some sort of loop.

The format of the data is as follows:

x.Product_Name = "product[x], product[y], product[z]"

As user selects multiple items from a list to search on.

I need to find anything within Product_Name that was selected from the user.

var names = JsonConvert.DeserializeObject<IEnumerable<string>>
(criteria.value).ToArray();

This line gets the items a user selected from the list and stores them in an array.

query = query.Where(x => names.contains(x.Product_Name)) 

Doesn't work because Product_Name is a flattened out version of products, so I can't do this.

What I need is something like the following:

foreach (string s in names)
{
    projectsQuery = projectsQuery.Where(x => x.Product_Name.Contains(s));
}

But when the SQL is created for the above, it uses an AND conditional instead of an OR conditional. I need to find any instances where string s is contained within the Product_Name .

You can achieve it by creating Expression tree manually. Although it is kind of hard to manage code.

var containsMethod = typeof(string).GetMethod("Contains", new[] { typeof(string) });

var xParameter = Expression.Parameter(typeof(x), "x");

var searchexpression = new stack<expression>();                                         
foreach (string s in names)
{
   var containsmethodexp = expression.call(Expression.Property(xParameter, "Product_Name", containsMethod, expression.constant(s));
    if (searchexpression.count == 0)
    {
        searchexpression.push(containsmethodexp);
    }
    else
    {
        searchexpression.push(expression.orelse(containsmethodexp, searchexpression.pop()));
    }
}

var finalResult = projectsQuery.Where(Expression.Lambda<Func<x, bool>>(searchexpression.pop(), new ParameterExpression[] { xParameter }));

here x is your Entity Name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM