C# Outer Apply in LINQ

前端 未结 3 1581
时光取名叫无心
时光取名叫无心 2021-02-04 08:47

How can I achieve Outer Apply in LINQ? I\'m having a bit of a problem.

Here\'s the SQL Query I\'m using.

SELECT u.masterID
      ,u.user
      ,h.created         


        
相关标签:
3条回答
  • 2021-02-04 09:20

    Outer Apply produces results of left outer join,
    the query should be:

    var q =
    from u in db.Users
    join h in db.UserHistory on u.masterID equals h.masterID into ps
    from p in ps.DefaultIfEmpty()
    select new { 
        masterID = u.masterID
        ,user = u.user
        ,created = ps.OrderByDescending(x=>x.created).FirstOrDefault()==null?null:ps.OrderByDescending(x=>x.created).First().created
    };
    
    0 讨论(0)
  • 2021-02-04 09:28
    from u in Users
    join UserHistory on u.masterID equals h.masterID into h
    select new {u.masterID, u.user, h.created.OrderByDescending().First()}
    
    0 讨论(0)
  • 2021-02-04 09:35
    from u in Users 
    join UserHistory on u.masterID equals h.masterID into h 
    select new {
      u.masterID,
      u.user,
      Created = h.Select(x => x.created).OrderByDescending(c => c).FirstOrDefault()
    }
    

    Or, with an association:

    from u in Users
    let created = u.UserHistories.Select(x => x.created).OrderByDescending(c => c).FirstOrDefault()
    select new
    {
      u.masterID,
      u.user,
      Created = created
    }
    
    0 讨论(0)
提交回复
热议问题