views:

281

answers:

3

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.

+3  A: 

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.

Jon Skeet
Yeah I'm populating the SelectList so I'm using all of the result set. That did the trick, cheers!
daddywoodland
A: 

Maybe this?

projBuildNos.Reverse().First().ID
Ryan Michela
+1  A: 

I found this on MSDN:

Queryable.LastOrDefault -- Returns the last element in a sequence, or a default value if the sequence contains no elements.

Mike Hofer
Might this involve another call to the db? If so, I figure I've got all the data there so just want to grab the last value.
daddywoodland