1

I have some list. I would like to change one or more values inside of it by using Lambda Expressions in Razor code especially with ForEach loop.

I don't know, It is possible or not, But my curiosity is more high to do with ForEach. I have to do this in Razor code not in the controller:

I take a reference from this Answer, BUT TRIED THE SAME SYNTAX IN RAZOR CODE:

@Html.DropDownListFor(model => model.months, new SelectList(Model.myList.Where(s => s.value == "1").ToList().ForEach(s => s.value = "January"), "id", "value")})

Update

Controller Code:

List<Digit> myList = bindMonth(12);

public static List<Digit> bindMonth(int maxvalue)
{
   List<Digit> monthList = new List<Digit>();
   maxvalue = maxvalue + 1;
   for (int i = 0; i < maxvalue; i++)
     {
         monthList.Add(new Digit(i, i.ToString()));
     }
    return monthList;
}

public class Digit
{
    public int id { get; set; }
    public string value { get; set; }
    public Digit(int id, string value)
    {
       this.id = id;
       this.value = value;
    }
}

It's throwing me Compilation Error in Browser.

enter image description here

Any help will be appreciated..!!!

Community
  • 1
  • 1
Smit Patel
  • 2,992
  • 1
  • 26
  • 44

1 Answers1

2

You have an unwanted } at end and that's what exactly your error statement saying. Remove that and it should be like below

@Html.DropDownListFor(model => model.months, new SelectList(Model.myList.Where(s => s.value == "1").ToList().ForEach(s => s.value = "January"), "id", "value"))

EDIT:

problem was, ForEach LINQ method which reurns a void and your SelectList() HTML helper method expects a IEnumerable<T>. make small change like below in your view page

Change the list first separately

@{
    ViewBag.Title = "My Stunning Page";
    Model.MyList.Where(s => s.value == "1").ToList().ForEach(s => s.value = "January");
}

use it in control

@Html.DropDownListFor(model => model.months, new SelectList(Model.MyList, "id", "value"))
Rahul
  • 76,197
  • 13
  • 71
  • 125