有没有办法使用lambda表达式编写此LINQ查询?

时间:2019-05-13 18:38:28

标签: c# entity-framework linq lambda webforms

我有一个linq查询,用于使用2个联接从3个表中获取数据。我更喜欢将其编写为lambda表达式,以便我的团队发现它更具可读性。有办法吗?我找不到任何合适的例子。

var q = (
     from sus in systemUserSessionManager.Get()
     join su in systemUserManager.Get() on sus.SystemUserId equals su.Id
     join p in personManager.Get() on su.PersonId equals p.Id
     where sus.EndTimeStamp >= oneDayAgo
     select new
     {
         Name = p.FirstName + " " + p.LastName,
         Email = su.Email,
         LastLogIn = sus.StartTimeStamp,
         LastSessionDurationInMinutes = 
             DbFunctions.DiffMinutes(sus.StartTimeStamp, sus.EndTimeStamp),
         LastActive = sus.EndTimeStamp
     }).ToList();

2 个答案:

答案 0 :(得分:4)

等效的lambda如下所示,假设Get()函数返回List

var q = systemUserSessionManager.Get()
    .Where(sus => sus.EndTimeStamp >= oneDayAgo)
    .Join(systemUserManager.Get(), 
        sus => sus.SystemUserId, 
        su => su.Id, 
        (sus, su) => new { sus, su })
    .Join(personManager.Get(), 
        j => j.su.PersonId, 
        p => p.Id, 
        (j, p) => new { sus = j.sus, su = j.su, p })
    .Select(x => new
    {
        Name = p.FirstName + " " + p.LastName,
        Email = su.Email,
        LastLogIn = sus.StartTimeStamp,
        LastSessionDurationInMinutes = 
            DbFunctions.DiffMinutes(sus.StartTimeStamp, sus.EndTimeStamp),
        LastActive = sus.EndTimeStamp
    })
    .ToList();

答案 1 :(得分:-2)

尝试这样的事情

var q = (
     from sus in systemUserSessionManager.Get()
     join su in systemUserManager.Get() on sus.SystemUserId equals su.Id
     join p in personManager.Get() on su.PersonId equals p.Id
     select new { sus = sus, su = su, p = p})
     .Where(x => x.sus.EndTimeStamp >= oneDayAgo)
     .Select(x => new {
         Name = x.p.FirstName + " " + x.p.LastName,
         Email = x.su.Email,
         LastLogIn = x.sus.StartTimeStamp,
         LastSessionDurationInMinutes = 
             DbFunctions.DiffMinutes(x.sus.StartTimeStamp, x.sus.EndTimeStamp),
         LastActive = x.sus.EndTimeStamp
     }).ToList();