daddywoodland
daddywoodland

Reputation: 1512

How to get the last object in a generic list?

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.

Upvotes: 1

Views: 4694

Answers (3)

Mike Hofer
Mike Hofer

Reputation: 17022

I found this on MSDN:

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

Upvotes: 1

Ryan Michela
Ryan Michela

Reputation: 8374

Maybe this?

projBuildNos.Reverse().First().ID

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1502406

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.

Upvotes: 5

Related Questions