Returning a single value with Linq to SQL(使用 Linq to SQL 返回单个值)
问题描述
我正在学习 Linq to SQL,但无法掌握它.我正在尝试使用 Linq 查询在 C# 中简单地返回单个(布尔值)值.
I'm learning Linq to SQL and I'm having trouble grasping it. I'm trying to simply return a single (boolean) value in C# with a Linq query.
我想看看故事的所有者是否希望在添加新评论时发送电子邮件通知.我希望包含 Linq to SQL 的方法返回一个布尔值.
I want to see if the owner of a story would like an email notification sent when new comments are added. I would like the method that contains the Linq to SQL to return a boolean value.
public bool NotifyOnComment(string username){
var notify = (from s in db.AccountSettings
where s.UserName == username
select s.NotifyOnComment).DefaultIfEmpty(false);
// clueless
}
更新:
我现在正在做以下事情:
I'm doing the following now:
var notify = (from s in db.AccountSettings
where s.UserName == username
select s.NotifyOnComment).SingleOrDefault();
return (bool)notify;
推荐答案
Linq,默认总是返回集合.如果您需要单个值,您可以应用 .Single(), .SingleOrDefault() 或 .First() 或 .FirstOrDefault() 方法.
Linq, by default always returns collections. If you need a single value, you can apply the .Single(), .SingleOrDefault() or .First() or .FirstOrDefault() methods.
他们在做什么方面略有不同.Single() 和 SingleOrDefault() 仅在结果中有恰好或最多条记录时有效.First() 和 FirstOrDefault() 会起作用,即使有更多的结果.
They differ slightly in what they do. Single() and SingleOrDefault() will only work if there is exactly or at most one record in the result. First() and FirstOrDefault() will work, even if there are more results.
如果结果不包含记录,*OrDefault() 变体将返回类型的默认值.
The *OrDefault() variants will return the default value for the type in case the result contained no records.
这篇关于使用 Linq to SQL 返回单个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 Linq to SQL 返回单个值
基础教程推荐
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- WPF 模态进度窗口 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
