LINQ expression inside foreach loop

In my View() i have many checkboxes with attr name="types". In my ActionResult I have a List types like parameter, and I do foreach loop to search in List, each type ID and add a Where() filter in my LINQ expression. If I select many types, the return is only one result and dont all what i chose. Look:

[HttpPost]
public ActionResult Index(List<int> types) {
  var variable = from s in MyViewModel select s;

  foreach(var type in types) {
    variable = variable.Where(x => x.TypesId == type);
  }

  return View(MyViewModel);
}

Is there another way to do this?

Thank you!!

Upvotes: 1

Views: 2506

Answers (4)

Mario Garcia
Mario Garcia

Reputation: 643

variable = variable.Where(x => types.Contains(x.TypesId));

This should give you all the values, if you only want one, add .FirstOrDefault() at the end

Upvotes: 3

Dmitri Trofimov
Dmitri Trofimov

Reputation: 763

The variable is being reset each foreach iteration. Create a List and add to it in foreach block.

Upvotes: 0

Hari Prasad
Hari Prasad

Reputation: 16956

There are few problems in your code, no matter what other part of code do your return statement always returns all MyViewModel collection.

Other problem is your code overwrite variable inside the loop.

I think, this is what you need.

return View(MyViewModel.Select(s=> types.Any(t=>t.type == s.TypesId));

Upvotes: 1

Friyank
Friyank

Reputation: 479

make attr name from name="types" to name="types[]"

and it will post array of selected values

Upvotes: 0

Related Questions