我有这行代码:
IQueryable<AZ_Return_R> fistSet = myDb.AZ_Return_Rs.Where(w => w.Master_Session_ID == 14);
List<AZ_Return_R> secondSet = myDb.AZ_Return_Rs.Where(w => w.Master_Session_ID == 14).ToList();
var res1 = fistSet.GroupBy(g => g.Order_ID).Select(s => new { orderId = s.Key, count = s.Key.Count()});
var res2 = secondSet.GroupBy(g => g.Order_ID).Select(s => new {orderId = s.Key, count = s.Key.Count()});
其中 AZ_Return_R
是一个包含 2 列的表:Order_ID
和 Master_Session_ID
。该表有 10 条记录,5 条 Master_Session_ID = 14
和 5 条 Master_Session_ID = 1
。 因为 Order_ID
在表中是唯一的,我假设 res1 和 res2 必须返回 5 条记录,所有 Count = 1
,结果 res1 是正确的,res2 返回 5 条记录,但是Count = 19
!!!
我哪里错了?
编辑
我发现如果我写:
var res3 = secondSet.GroupBy(g => g.Order_ID).Select(s => new { orderId = s.Key, count = s.Count() });
结果是正确的,那么为什么 List<> 必须使用 s.Count 而 IQueryable<> 必须使用 s.Key.Count ?
最佳答案
当您在下一个 Select
参数 s
中按 Order_ID
分组时,您的示例逻辑有误 Key
相同的 Order_ID
- 在您的案例中为字符串。
因此,当您在选择中调用 Key.Count()
时,它会返回字符串长度
所以你需要改变
s.Key.Count()
到
s.Count()
更新
您的解决方案适用于 IQueryable
,因为它首先生成类似的 sql 脚本
SELECT COUNT(*) AS [count], [t0].[Order_ID] AS [orderId]
FROM [dbo].[TestTable] AS [t0]
WHERE [t0].[Master_session_ID ] = @p0
GROUP BY [t0].[Order_ID]
当你测试结果时执行它。如您所见,此 sql 返回正确的值
在 IEnumerable
情况下,您首先获取所有项目,然后使用 Linq-to-Objects 来处理它们。
关于c# - 使用 GroupBy 和 Count 在 Linq 中产生不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20775067/