Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Index was out of range when expression converted to linq expression

I am creating a collection of select list items from my userGroupsRepository. I know that there are two records.

Is there something what i am doing wrong?

At first i have written following code as i thought this is a faster way to get my select list item collection, where i have "this._userGroupRepository.All" as IQueryable

my collection is:

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

this implementation however results with

Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index

and here i have my implementation of collection with 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()});
            }
like image 981
cpoDesign Avatar asked Nov 13 '22 18:11

cpoDesign


1 Answers

Does it help to make an Enumerable of your Queryable?

this._userGroupRepository.All.AsEnumerable().Select(
like image 179
StriplingWarrior Avatar answered Dec 11 '22 05:12

StriplingWarrior