使用 Linq to SQL 返回单个值

Returning a single value with Linq to SQL(使用 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 返回单个值

基础教程推荐