I am stuck on this. I have two tables: Users2Users and ActivityLog. I want to look up the list of Users2Users that are a user’s friends and return each of their latest activity based on its Timestamp, then check what type it is.
Users2Users
int UserId
int TypeOfLink
int FriendId
ActivityLog
int Type
int UserId
DateTime Timestamp
The thing that seems to be troubling me is getting the ActivityLog entity rather than its Timestamp value.
My friendList query looks like this:
var friendList = (from u in db.Users2Users
where u.UserId == userId || u.FriendId == userId
&& u.TypeOfLink == 2 // confirmed as friend
orderby u.User.ScreenName ascending
select u).Distinct().ToList();
After that I was going to try a foreach, but how do I return the ActivityLog entity rather than the Timestamp?
// get their last activity
foreach (var user in domusers)
{
var act = (from a in db.ActivityLogs
where a.UserId == user.UserId
select a.Timestamp).Max();
// other stuff
}
You can order the entries by
Timestampand the pick the first element:Or using query syntax:
Note that if there are no elements in the source collection you will get a
nullresult.Using
OrderByDescendingis slightly ineffecient because it will sort all the activities. It is more efficient to perform a single pass over the collection and find the element with the latestTimestamp. You can do that usingAggregate. Here I assume that you are able to create a “null”Activitywhere theTimestampproperty has the default (and minimal value) forDateTime:If you can’t create a “null” activity as the seed for
Aggregateyou can use an anonymous type to keep track of the latest timestamp and the associated activity but it is slightly more tedious to do.