gpt4 book ai didi

c# - 在 linq 中选择 Count(Id)

转载 作者:太空狗 更新时间:2023-10-29 18:19:56 25 4
gpt4 key购买 nike

有什么方法可以编写 linq 查询以产生:

select Count(Id) from tbl1

因为

tbl1.Select(q=>q.Id).Count()

没有转化为我想要的结果

更新:

它返回:

select count(*) from tbl1

回答后更新:

我测试了超过 21,000,000 的场景

execution plan

record counts

最佳答案

Is there any way to write a linq query to result in.

没有。首先要了解你需要什么,例如,在 T-SQL 中,你可以使用:

  • COUNT(*) 将计算表中的行数
  • COUNT(column) 将对列中的条目进行计数 - 忽略空值。

如果你需要计算你有多少行,只需使用

var total = tbl1.Count();

如果您需要查看特定列不为空的实体有多少,请使用 Count 方法的过滤器重载。

var total = tbl1.Count(x => x.Id != null);

不,这是不可能的。使用 Count(*) 或 ´Count(Id) 时,性能没有差异,如果您的 Id` 是主键,则更是如此。

我在这里用超过一百万个元组的表做了一个实验。查看两个查询的执行计划。第一个是 select count(*),第二个是 select count(id)id 是主键(抱歉结果是葡萄牙语-巴西):

enter image description here

关于c# - 在 linq 中选择 Count(Id),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33781540/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com