tags:

views:

911

answers:

2

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 LastActivityUtc out 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;
            }
+1  A: 

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

startDate = postTimes.Take(100).ToList().Last().Value;
Brandon
This would work but not for the reason you mentioned. `.AsEnumerable()` instead of `.ToList()` would also work. The reason these two work is that they don't try to translate the expression to SQL. They just retrieve 100 rows and process it on the client.
Mehrdad Afshari
My mistake, I'll remove that part of my answer.
Brandon
+5  A: 

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...

Jon Skeet
Rats, apparently, my initial answer wasn't stupid at all! I blame it on Marc ;)
Mehrdad Afshari
@Mehrdad - I humbly accept the responsibility!
Marc
Who is more foolish? The fool, or the fool who follows him?
Marc Gravell
@Marc Phillips - I think he was referring to my deleted answer...
Marc Gravell
@Marc - well, don't blame me that you share my devilishly handsome name. ;)
Marc
Marc: I'm speechless ;)
Mehrdad Afshari
@Marc Gravell: I meant it as a joke. Sorry if ...
Mehrdad Afshari
Lol - I just checked, and actually our posts are virtually identical. It just so happens that I was watching when me and Mehrdad deleted our answers around each-other in a dance of mutual destruction. Re the name... if only people would stop "correcting" it to Mark ;-p
Marc Gravell