Mike Payne
Mike Payne

Reputation: 107

How to use multi-valued/array parameter(enum values) obtained from Request.Query in LINQ queries?

I'm still new to modern styles .NET development and Entity Framework. I'm trying to get a list of objects where one of the values falls in a list of other values, and I'm trying to use the LINQ query methods to do so.

string cb_orderstatus = Request.Query["OrderStatusSearch"].ToString();
if (!string.IsNullOrEmpty(cb_orderstatus))
{
    string[] orderStatuses = cb_orderstatus.Split(",");
    query = query.Where(o => orderStatuses.Contains(o.Status.ToString()));
}

If the value of the cb_orderstatus is a string array containing 5, 10, and 15, I want the query to return objects where their Status equals any of these values. Currently it is not working. Can anyone help?

Upvotes: 1

Views: 182

Answers (1)

Eugene Podskal
Eugene Podskal

Reputation: 10401

It is an educated guess, but as you say that

o.Status is an OrderStatus enum

then most probably you need to convert values from cb_orderstatus to actual OrderStatuses values and use OrderStatus[].Contains in the query

string cb_orderstatus = Request.Query["OrderStatusSearch"].ToString();
if (!string.IsNullOrEmpty(cb_orderstatus))
{
    var orderStatuses = cb_orderstatus
        .Split(",")
        .Select(statusIntegerString => 
            (OrderStatus)int.Parse(statusIntegerString))
        .ToArray();
    query = query.Where(o => orderStatuses.Contains(o.Status));
}

Though I am not sure that you will get comma-separated values from Request.Query["OrderStatusSearch"].

In any case, it would be orders of magnitude better to rely on standard parameter binding, so I'd recommend you to post another question that deals with

I have a property on the model class that has [BindProperty] on it and is of type List but it is not being populated with any data.

Upvotes: 2

Related Questions