Linq,将列表加入另一个列表中的最后一项

时间:2014-11-30 12:32:08

标签: c# linq join

我有一个用户列表和另一个用户活动列表。 我想获得用户列表,包括用户上次活动。 我试过这个:

var usersActivity = 
  from user in Users
  join activity in Activities on user.Id equals activity.UserId
  group activity by activity.UserId into UserActivities
  select new {
     activity=UserActivities.OrderByDescending(g=>g.DateTime).First(),
     user=user
  }

但它不起作用。它说:当前上下文中不存在“用户”这个名称

我加入或分组是错误的吗?

2 个答案:

答案 0 :(得分:1)

您可以使用更简单的方法:

var usersActivity = 
 from user in Users
 select new {
    activity=Activities.Where(a => a.UserId = user.Id).OrderByDescending(a => a.DataTime).FirstOrDefault(),
    user=user
 }

答案 1 :(得分:1)

尝试按用户分组而不是用户ID:

var usersActivity =
    from user in Users
    join activity in Activities on user.Id equals activity.UserId
    group activity by user into UserActivities
    select new
    {
        activity = UserActivities.OrderByDescending(g => g.DateTime).First(),
        user = UserActivities.Key
    };