14

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;
Mike
  • 2,912
  • 4
  • 31
  • 52

4 Answers4

29

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.

Joey
  • 344,408
  • 85
  • 689
  • 683
  • Now what if there's a chance (and there will be) that no record exists yet. Which of those three would be best in that situation? – Mike Oct 09 '09 at 15:00
  • To be precise, a working solution might require more than just that, so look below to Justin's answer. He probably got exactly what you need. – Joey Oct 09 '09 at 15:08
9
var notify = (from s in db.AccountSettings
              where s.UserName == username
              select s.NotifyOnComment).DefaultIfEmpty(false).First();

//notify will either hold a bool or the AccountSettings object so
return (!(notify == false)); // Thanks Nick. Amazing what you'll do in a hurry.
Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
4
var notify = (from s in db.AccountSettings
              where s.UserName == username
              select s.NotifyOnComment).Count();

return  Convert.ToBoolean(notify);
Necro
  • 41
  • 1
1

If you expect just one result just use Single or SingleOrDefault to get the bool. If you want the first result you can use First or FirstOrDefault.

bruno conde
  • 47,767
  • 15
  • 98
  • 117