Linq to objects error: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
I am getting the following error when trying to return a list of new objects from a linq query. I am looking to return a stripped down entity for use in a selectbox and only need and id and name.
Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
myViewModel.Regions = _regionRepository
.OrderBy(x => x.Name)
.Se开发者_Python百科lect(x => new RegionForSelect {Id = x.Id.ToString(), Name = x.Name})
.ToList();
public class MyViewModel
{
public IList<RegionForSelect> Regions { get; set; }
}
public class RegionForSelect
{
public string Id;
public string Name;
}
Not sure where I am going wrong here.
Any tips appreciated.
Is there any data in the collection? LINQ-to-NHibernate has a problem not resulting in an empty List<T>
sometimes, but instead this error. It can also be thrown when calling any parameter-less method against an empty field, or if the method has no parameters.
First, try updating your nHibnerate LINQ version, there have been lots of improvements. If that fails, then try this (since you're working in memory anyway with Linq-to-Objects) to take the nHibernate provider out of the picture:
myViewModel.Regions = _regionRepository.All()
.OrderBy(x => x.Name)
.Select(x => new RegionForSelect {Id = x.Id.ToString(), Name = x.Name})
.ToList();
If that still fails, replace .All()
with .ToList()
, this is not ideal in terms of performance or memory usage, but may be your only choice. This kind of stuff that should just work is also why nHibernate and I went our separate ways some time ago :)
精彩评论