0

I have below variables

public IEnumerable<SelectListItem> SelectedGroups { get; set; }
Dictionary<string,string> grpsList;

Below is my iteration

if(condition)
 viemodel.SelectedGroups = selectlist1;
else
  viemodel.SelectedGroups = selectlist2;

foreach (var item in viemodel.SelectedGroups) <<--Error message
       grpsList.Remove(item.Value);

I am not modifying selectedgroups but using it as a reference to remove from grpsList but its failing in foreach declaration.


Added code, selectlist1 contains reference to grpsList, something like this (removed additional joins and all other code)

from g in grpsList
select g).ToSelectList(g => g.Value, g => g.Key);

selectlist2 is different list.

Sunny
  • 4,765
  • 5
  • 37
  • 72

2 Answers2

2

Most likely SelectedGroups point to a linq expression that involves grpsList. To avoid this problem do a .ToList() before the assigment to SelectedGroups. (You can still keep the property signature as IEnumerable<SelectListItem>)

Using your added code:

from g in grpsList
select g).ToSelectList(g => g.Value, g => g.Key).ToList(); <-- here

Note that if you do not do the ToList() on a linq expression than every time you iterate the Enumerator the complete linq statement is evaluated. This can cause a lot of unnecessary performance issues.

Magnus
  • 45,362
  • 8
  • 80
  • 118
2

You can try with

foreach (var item in viemodel.SelectedGroups.ToList<SelectListItem>()) 
{
       grpsList.Remove(item.Value);
}
Aghilas Yakoub
  • 28,516
  • 5
  • 46
  • 51