LinqToSql 中的标量函数

发布于 2024-07-20 21:25:14 字数 211 浏览 15 评论 0原文

在 ADO.Net/SQLClient 中我经常会做这样的事情:

从 SomeTable WHERE SomeKey = 1234 中选择 COUNT(*)

...并使用executescalar 触发它以返回count 的值 - 用于简单检查是否存在某些内容。

我如何使用 LinqToSql 做同样的事情?

In ADO.Net/SQLClient I would often do something like this:


SELECT COUNT(*) FROM SomeTable WHERE SomeKey = 1234

...and fire it using executescalar to return the value of count - for a simple check if something exists.

How would I do the same using LinqToSql?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

秋日私语 2024-07-27 21:25:14
if (context.SomeTable.Any(row => row.SomeKey == 1234))
{
    DoStuff();
}

您还可以使用Count()

if (context.SomeTable.Count(row => row.SomeKey == 1234) > 0)
{
    DoStuff();
}

但这需要始终遍历所有行,而 Any() 可以在第一个匹配行之后返回 - 因此 Any() 可能具有更好的性能。

if (context.SomeTable.Any(row => row.SomeKey == 1234))
{
    DoStuff();
}

You could also use Count().

if (context.SomeTable.Count(row => row.SomeKey == 1234) > 0)
{
    DoStuff();
}

But this requires always to go through all rows while Any() can return after the first matching row - so Any() might have better performance.

回忆躺在深渊里 2024-07-27 21:25:14

请记住,Linq to Sql 是延迟执行,这意味着查询仅在您访问集合时才实际执行。 因此:

var q = (from p in db.SomeTable
        where p.SomeKey == 1234
        select p).Count();

将在 SQL 方面变成 SELECT Count()。

Remember, Linq to Sql is deferred execution, which means, the query only actually executes when you access the collection. Therefore:

var q = (from p in db.SomeTable
        where p.SomeKey == 1234
        select p).Count();

Will turn into a SELECT Count() on the SQL side of things.

日暮斜阳 2024-07-27 21:25:14

如果您想查看某些内容是否存在,您可以使用 any 函数:

if (context.SomeTable.Any(i => i.SomeKey == 1234))
{
    return true;
}

或者如果您实际上想知道计数,您可以使用 where 函数和 count 函数:

context.SomeTable.Where(i=> i.SomeKey == 1234).Count();

If you're looking to see if something exists you can use the any function:

if (context.SomeTable.Any(i => i.SomeKey == 1234))
{
    return true;
}

or if you actually want to know that count you can use the where function and the count function:

context.SomeTable.Where(i=> i.SomeKey == 1234).Count();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文