Chris
Chris

Reputation:

.NET: LINQ's Last()

I'm new to LINQ and LINQ to SQL and don't understand what's wrong with this code. The Excetpion.Message I get is

"Query operator 'Last' is not supported."

What I'm trying to do is get the earliest LastActivityUtcout of the latest 100. The code follows.

var postTimes = from post in db.Post
                where post.LastActivityUtc != null
                orderby post.LastActivityUtc descending
                select post.LastActivityUtc;

DateTime startDate = DateTime.MinValue;

if (postTimes.Count() >= 2)
{
    startDate = postTimes.Take(100).Last().Value;
}

Upvotes: 9

Views: 19278

Answers (2)

Brandon
Brandon

Reputation: 70032

Call .ToList() on postTimes and then try using .Last()

startDate = postTimes.Take(100).ToList().Last().Value;

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1503489

Brandon has posted a solution, but it requires copying the whole list in memory.

If you just want to "transition" from database queries to in-process, you can use AsEnumerable:

startDate = postTimes.Take(100).AsEnumerable().Last().Value;

Having said that, you possibly do want to call ToList(), but earlier - to avoid having to execute the query once for the count, and once for the last value:

var postTimes = (from post in db.Post
                where post.LastActivityUtc != null
                orderby post.LastActivityUtc descending
                select post.LastActivityUtc).Take(100).ToList();

DateTime startDate = DateTime.MinValue;

if (postTimes.Count >= 2)
{
    startDate = postTimes.Last().Value;
}

That will execute the database query once, but only fetch the first 100 records into memory. Of course, it falls down somewhat if you were going to use postTimes elsewhere...

Upvotes: 19

Related Questions