Ayman H
Ayman H

Reputation: 185

ASP.NET Web API GET Method: Passing multiple values for single parameter

I am fairly new to ASP.NET Web API.

I am trying to build an API method that can handle multiple values for a single parameter from a search client.

The criteria needs to be a OR search for eg. A color search for Red OR Blue OR Green.

I pass the colors as integer to my method. Please find my controller method below which fails to compile with the following error

Errors:

Error 1 'int' does not contain a definition for 'Contains' and the best extension method overload 'System.Linq.ParallelEnumerable.Contains(System.Linq.ParallelQuery, TSource)' has some invalid arguments

Error 2 Instance argument: cannot convert from 'int' to 'System.Linq.ParallelQuery'

Code:

public IQueryable<Items> GetItemByColour(string Colour)
{
    int[] intArr = Array.ConvertAll(Colour.Split(','), s => int.Parse(s));

    var query = from a in db.Items
                where a.ItemsColour.Contains(intArr)
                select a;

    return query;
}

Upvotes: 6

Views: 2024

Answers (2)

Lajos Arpad
Lajos Arpad

Reputation: 76508

I suppose this will be the solution to your issue:

public IQueryable<Items> GetItemByColour(string Colour)
{
    List<int> intArr = Array.ConvertAll(Colour.Split(','), s => int.Parse(s)).ToList();

    var query = from a in db.Items
                where a.intArr.Contains(ItemsColour)
                select a;

    return query;
}

The problem was that you were looking for the presence of an array in an int. You need to look for the presence of an int in the array

Upvotes: 0

Meryovi
Meryovi

Reputation: 6231

You seem to have two different issues there. The first one is that you don't need to send the Colors list as a string and convert it to an integer array manually, you can do it like this instead:

public IQueryable<Items> GetItemByColour([FromUri] int[] Colour)

And you're getting an error in your LINQ query because a.ItemColour is an integer, not an integer list, therefore you can't use the Contains extension method on it. You have to do it like this (assuming Colour is now an integer array):

var query = from a in db.Items
            where Colour.Contains(a.ItemsColour)
            select a;

return query;

Upvotes: 4

Related Questions