通过查询将组转换为linq

时间:2014-10-16 14:33:21

标签: c# linq

我正在尝试在linq中转换下面的查询

 select ta.id, ta.name, min(tb.id) from tableA ta
 left join tableB tb on tb.fkid=ta.id
 group by ta.id, ta.name

我在下面试过

 var query = (from tableA in tableARepository.AsQueryable()
            join tableB in tableBRepository.AsQueryable() on
                tableA.Id equals tableB.fkid

                     group grp by new {tableA.Id, tableA.Name } into groupedCol
                     select new
                     {
                         Id = groupedCol.Key.Id,
                         Name = groupedCol.Key.Name,
                         fkId = grouppedCol.Min // cant get column fkid from tableB

                     }

            );

我无法获得fkid

tableB列的最小值

这里缺少什么或如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

我认为您正在寻找GroupJoin

from tableA in tableARepository.AsQueryable()
join tableB in tableBRepository.AsQueryable() on
tableA.Id equals tableB.fkid into tb
select new 
       {
           Id = tableA.Id,
           Name = tableA.Name,
           fkId = tb.Min(x => x.id)
       } 

答案 1 :(得分:1)

您应该能够在不使用JoinGroupBy的情况下获得所需的结果:

var restrictTo = new[] {1, 2};
var query = tableARepository.AsQueryable()
    // I want to add where clause like tableA.Id in (1,2)
    .Where(a => restrictTo.Contains(a.Id))
    .Select(a => new {
        Id = a.Id
    ,   Name = a.Name
    ,   FkId = tableBRepository.AsQueryable().Min(b => b.fkid=a.id)
    });