Skip to main content
 首页 » 编程设计

c#之我在构建 Linq 查询时做错了什么

2024年02月20日13oomusou

我正在尝试为以下查询编写等效的 linq 代码。

SELECT A.*   
FROM   
(   
    SELECT * FROM TableA    
    WHERE id = 100   
) a   
JOIN    
(   
    SELECT Name, MAX(AnotherId) AnotherId    
    FROM TableA    
    WHERE id = 100   
    GROUP BY Name    
) b   
on a.Name  = b.Name and a.AnotherId = b.AnotherId    

这是linq

var Collection = from R in DbContext.TableA   
join G in (DbContext.TableA.Where(r => r.Id == 100).GroupBy(r => new { r.Name, r.AnotherId } ).Select(g => new { Name = g.Name , AnotherId = g.Max(o => o.AnotherId) }))   
on new { R.Name, R.AnotherId } equals new { G.Name, G.AnotherId }   
where R.Id == 100   
select R;   

但我收到以下编译错误,我不知道如何修复。任何想法

连接子句中的一个表达式的类型不正确。调用“Join”时类型推断失败。

错误 7 'System.Linq.IGrouping' 不包含 'Name' 的定义,并且找不到接受类型为 'System.Linq.IGrouping' 的第一个参数的扩展方法 'Name'(您是否缺少使用指令还是程序集引用?)

请您参考如下方法:

当您只想按 r.Name 分组时,您按 r.Name、r.AnotherId 分组。

var Collection = from R in DbContext.TableA   
join G in (DbContext.TableA 
                      .Where(r => r.Id == 100) 
                      .GroupBy(r => r.Name) 
                      .Select(g => new { Name = g.Key , AnotherId = g.Max(o => o.AnotherId) }))   
on new { R.Name, R.AnotherId } equals new { G.Name, G.AnotherId }   
where R.Id == 100   
select R;  

并使用 Fluent Syntax

var collection = DbContext.TableA 
                          .Where(t1 => t1.Id == 100) 
                          .Join(DbContext.TableA 
                                .Where(t2 => t2.Id == 100) 
                                .GroupBy(t2 => t2.Name) 
                                .Select(group => new{Name = group.Key,  
                                                      AnotherId = group.Max(e => e.AnotherId)}) 
                                 ), 
                                 t1 => new{t1.Name, t1.AnotherId} , 
                                 t2 => new{t2.Name, t2.AnotherId}, 
                                 (t1, t2) => t1);