从linq投影中获取逗号分隔列表

时间:2013-06-10 20:12:07

标签: c# linq entity-framework-4

    var users = from u in db.Users.Include("UserLogins")
      join ul in db.UserLogins on u.UserId equals ul.UserId
      join ua in db.UserActions ON ul.UserLoginId = ua.UserLoginId
      where u.IsActive = true
      group new { ul, ua }
        by new {u.UserId} into proj

    select new 
    {
    UserId = (Int32)y.Key.UserId,
        LoginDates = ????????
    };

是否可以在投影中返回日期列表集合?

我猜不到,逗号分隔的日期列表怎么样?

类似的东西:

"DateTime1, Datetime2, DateTime3"

2 个答案:

答案 0 :(得分:0)

我希望我能正确理解你的问题......

var users =
  from u in db.Users
  where u.IsActive
  select new
  {
    u.UserId,
    LoginDates =
      from d in u.LoginDates
      select d.LoginDate,
  };

这会使LoginDates成为IEnumerable LoginDate的{​​{1}}(可能是IEnumerable<DateTime>)。如果愿意,您可以随后创建一个以逗号分隔的列表。

答案 1 :(得分:0)

  

是否可以在投影中返回日期列表集合?

当然,每个分组都会实现IEnumerable,因此您可以使用ToList

select new 
{
    UserId = (Int32)y.Key.UserId,
    LoginDates = y.Select( i => i.LoginDate).ToList()
};
  

逗号分隔的日期列表怎么样?

只需使用String.Join

var users = (from u in db.Users.Include("UserLogins")
  join ul in db.UserLogins on u.UserId equals ul.UserId
  join ua in db.UserActions ON ul.UserLoginId = ua.UserLoginId
  where u.IsActive = true
  group new { ul, ua }
    by new {u.UserId} into proj)
.AsEnumerable()  // Hydrate the query
.Select(y=> new 
{
    UserId = (Int32)y.Key.UserId,
    LoginDates = string.Join(",",
                             y.Select( i => i.LoginDate
                                             .ToString("yyyy-MM-dd")
                                     ).ToArray()
                            )
});