I’m doing a linq-to-sql query and I wish the LastOrDefault operator were available but it’s not. So, I’m writing the query like this:
TheUserNote = ((from note in MyDC.UserNotes
where note.UserID == TheUserID
select note.NoteText).Skip(
(from n in MyDC.UserNotes
where n.UserID == TheUserID
select n.NoteID).Count() - 1)).SingleOrDefault(),
Basically, I want to use Skip and Count to get to the last item: count how many items there are, substract 1, and skip for that number.
It’s not working and I’m looking to fix it. The problem is that sometimes Count can be 0 so I get an error saying parameters are not valid since in that case Count will be -1.
Any suggestions?
Thanks.
You might try
.Reverse().FirstOrDefault(), or if you have a date column or primary key column try.OrderByDescending(...).FirstOrDefault().Using your variable names and comment: