I am passing a populated SelectList to my View and I want to default the selected value to the last record in the list. So far I've got:
IQueryable<BuildNumber> projBuildNos = tcRepository.GetProjectBuildNos();
BuildList = new SelectList(projBuildNos, "ID", "value", projBuildNos.Last().ID);
I get an exception saying "the query operator 'Last' is not supported but I can't seem to get at the last record in my generic list and can't find any examples.
This code is from a 'form view model' passing select lists from my repository back to the view and I think I should be performing this here. However I'm new to generics/mvc/linq so am happy for alternative suggestions.
Thanks in advance for any help. Please let me know if you want any more 开发者_开发知识库info.
Are you already going to suck all the results from your query into memory? If so, I suggest you execute your query and get the result into a list:
List<BuildNumber> projBuildNos = tcRepository.GetProjectBuildNos().ToList();
BuildList = new SelectList(projBuildNos, "ID", "value", projBuildNos.Last().ID);
Otherwise you could easily end up with a workaround which executes the query twice - possibly giving inconsistent results.
I found this on MSDN:
Queryable.LastOrDefault -- Returns the last element in a sequence, or a default value if the sequence contains no elements.
Maybe this?
projBuildNos.Reverse().First().ID
精彩评论