1

I have a MVC web application with multiple selects that allow multiple selections that the user can use to filter data. For example: A car database where the user can select by make, color and body style. A possible search would be (Red OR Blue) AND (Chevy OR Ford) AND (SUV). I have all the selects returned in my viewmodel as array of strings and all gets returned to my controller correctly. I have the Color array with 'Red' and 'Blue', the Model array with 'Chevy' and 'Ford' and the BodyStyle array with 'SUV'. Now that I have the model posted to the controller, how do I construct the linq statement that will allow and of these criteria to me blank or contain multiple selections?

Model:

public class SearchViewModel
{
    public string[] Model { get; set; }
    public string[] Color { get; set; }
    public string[] Body { get; set; }
}

Controller:

public ActionResult Search(SearchViewModel search)
{
    //TODO: Create linq for all search criteria
    List<Cars> cars = db.Cars.Where(car => car.Model == search.Model[0]);

    return View(cars);
}
2
  • 1
    can you give us a sample of you data where you want to perform the LINQ? Commented Aug 4, 2014 at 20:01
  • Welcome to Stack Overflow. You have a great description of what you are attempting to do, but have provided no code. Please take a minute to read Help Center > Asking > How do I ask a good question?. It will benefit both you and the people trying to help you. Commented Aug 4, 2014 at 20:03

1 Answer 1

1
var list = new List<string> { "red", "orange"};

    from c in DB.Cars
    where list == null || list.Contains(c.Color)
    select c;
Sign up to request clarification or add additional context in comments.

2 Comments

When I try 'db.Cars.Where(car => search.Color== null || search.Color.Contains(car.Color)).ToList();' I get an error when doing the check for null: Cannot compare elements of type 'System.Collections.Generic.List`1'. Only primitive types, enumeration types and entity types are supported.
I initialize my list in the SearchViewModel and check if list count is zero: List<Car> cars= db.Car.Where(car => search.Color.Count == 0 || search.Color.Contains(car.Color)).ToList();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.