使用LINQ返回一个值到SQL [英] Returning a single value with Linq to SQL

查看:178
本文介绍了使用LINQ返回一个值到SQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在学习LINQ to SQL和我无法抓住它。我想简单地返回在C#单(布尔)值与LINQ查询。

我想看看故事的主人想在添加新的评论发送电子邮件通知。我想包含LINQ到SQL该方法返回一个布尔值。

 公共BOOL NotifyOnComment(用户名字符串){
        VAR通知=(从s在db.AccountSettings
                      其中,s.UserName ==用户名
                      选择s.NotifyOnComment).DefaultIfEmpty(假);        //无能
    }

更新:

我做的,现在以下内容:

  VAR通知=(从s在db.AccountSettings
                      其中,s.UserName ==用户名
                      选择s.NotifyOnComment).SingleOrDefault();        返回(布尔)通知;


解决方案

LINQ中,默认情况下总是返回集合。如果你需要一个值,你可以将 。单() .SingleOrDefault() 。首先() .FirstOrDefault() 方法。

他们他们做了什么略有不同。 单()的SingleOrDefault()如果只会工作的究竟最多的结果中的一个记录。 第一() FirstOrDefault()将工作,即使有更多的结果。

* OrDefault()变种将返回的情况下,该类型的结果包含任何记录的默认值。

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.

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
    }

Update:

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, by default always returns collections. If you need a single value, you can apply the .Single(), .SingleOrDefault() or .First() or .FirstOrDefault() methods.

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.

The *OrDefault() variants will return the default value for the type in case the result contained no records.

这篇关于使用LINQ返回一个值到SQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆