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

标签 c# linq

我正在尝试为以下查询编写等效的 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);

关于c# - 我在构建 Linq 查询时做错了什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11191954/

相关文章:

c# - 模板/泛型类中的非常量静态成员 - C++ 与 C#

c# - 为什么 .NET Framework 4.0 中的 mscorlib 版本是 4.6.x?

linq - 如何计算嵌套集合/代码优先 Entity Framework 中的项目

c# - 如何将 Union 与不同类型的集合一起使用?

c# - 使用 dotnet cli 命令将文件夹添加到 C# 项目

c# - Service Fabric Actor 状态就像一个队列

c# - 如何从 C# 可移植类库 (PCL) 添加对 F# 可移植库的引用

c# - 数组中数字的排列

c# - 对 ISet 集合的 Linq 查询

c# - 如何测试我的 Linq IQueryable 是否已执行