在 Distinct() 之后获取 IQueryable 集合的实际计数
我的代码:
IQueryable<string> keys = dr.Localization.GetQuery().Select(x => x.Key).Distinct();
int count = keys.Count();
集合keys
在distinct后有正常的集合,这很好。 但是在keys.Count()
中,我有表中所有行的数量,没有不同。 我的 ORM 是 NHibernate。
我该怎么做才能获得 IQueryable 集合的实际计数?(无需转换为其他集合类型)
谢谢!
My code:
IQueryable<string> keys = dr.Localization.GetQuery().Select(x => x.Key).Distinct();
int count = keys.Count();
Collection keys
has normal collection after distinct, it's good.
But in keys.Count()
, I have number of all rows of table without distinct.
My ORM is NHibernate.
What can i do to have real count of IQueryable collection? (without casts to other collection types)
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的可查询提供程序似乎有问题,您应该报告该错误。
同时,正确获取计数的一种方法是使用keys.AsEnumerable().Count()。但是,这会导致对整个集合的评估。因此,如果生成的集合有很多项目,您将检索所有项目只是为了获得计数。
您可以尝试的另一个选择是使用类似
keys.GroupBy(k => k).Count()
的方法,或者可能在没有Distinct()
的情况下使用相同的方法并希望在这种情况下也不存在相同的错误。It seems your queryable provider is buggy, you should probably report that bug.
In the mean time, one way to get the count correctly would be to use
keys.AsEnumerable().Count()
. BUT, this will cause the evaluation of the whole collection. So, if the resulting collection has many items, you will retrieve them all just to get the count.Another option you could try is to use something like
keys.GroupBy(k => k).Count()
, or possibly the same without theDistinct()
and hope the same bug isn't present in this case too.除非对 Count() 的调用未转换为仅选择计数的 SQL 查询,否则 Count() 扩展方法必须枚举所有对象。由于您已将键放入变量中,我假设您稍后需要它,可能会枚举它。所以你可以像这样在这里获取它们
但是我很好奇,在你的示例中这会产生什么(查询和结果):
Unless the call to Count() is not transformed into an SQL query that selects just the count, the Count() extension method has to enumerate all objects anyway. Since you have put keys in a variable I assume you're needing it later on, possibly enumerating it. So you could fetch them all right here like so
But I'm curious, in your example what does this produce (query and result):