Index was out of range when expression converted to linq expression

I am creating a collection of favorites list items from my userGroupsRepository. I know there are two entries.

Is there something I'm doing wrong?

I wrote the following code first, as I thought it was a faster way to get my collection of favorites list items, where I have "this._userGroupRepository.All" as IQueryable

My collection:

List<SelectListItem> listItems = this._userGroupRepository.All.Select(
           userGroup => new SelectListItem() { 
                                   Text = userGroup.GroupName, 
                                   Value = userGroup.UserGroupId.ToString() 
           }).ToList();

this implementation, however, is obtained using

The index was out of range. Must be non-negative and smaller than the size of the collection. Parameter Name: Index

and here I have my collection implementation rewriting it as foreach

  List<SelectListItem> listItems = new List<SelectListItem>();
            foreach (UserGroup userGroup in this._userGroupRepository.All)
            {
                listItems.Add(new SelectListItem(){
                                                Text = userGroup.GroupName, 
                                                Value = userGroup.UserGroupId.ToString()});
            }
+5
source share
1

Queryable?

this._userGroupRepository.All.AsEnumerable().Select(
+1

All Articles