2

In both of the statements I am trying to fetch the ID of Category which has the name as specified in the variable;

Both work fine. What is the difference and which one is better?

string name = "Progreammers";

var categoryID = from c in DataContext.Categories
                             where c.Name == name
                             select c.CategoryID;

var categoryID  = 
  DataContext.Categories.Single(c => c.Name == name).CategoryID;

EDIT: There is only one Name(field) for every CategoryID(field) in the table.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Asad
  • 21,468
  • 17
  • 69
  • 94

3 Answers3

12

The two statements perform different functions.

The first could return multiple records.

The second will only return a single CategoryID. It will also throw an exception if at least one record is not found.

The following query would be the equivalent to your first statement:

var categoryID = DataContext.Categories.Where(c => c.Name == name).CategoryID;

And the following is the query syntax equivalent to the second statement:

var categoryID = (from c in DataContext.Categories
                 where c.Name == name
                 select c.CategoryID).Single();

Either way, consistency is probably the most important (performance should be on par with each other since they're both executed the same way). If you use query syntax, stick with it. If you start using lambda expressions, use them as much as you can.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
3

They are not the same.

The first one will return a list if there are many matches.

The second one will only return one.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Fredou
  • 19,848
  • 10
  • 58
  • 113
0

As already noted the two are different but I think the purpose of your question is asking if there is a difference between "SQL" style and "Lambda" style LINQ expressions.

If so, there is a similar question here:

LINQ: Dot Notation vs Query Expression

Community
  • 1
  • 1
HitLikeAHammer
  • 2,679
  • 3
  • 37
  • 53
  • Query syntax is really just converted into the lambda syntax by the compiler, so as long as both statements are truly written to do the same thing they are equivalent. – Chris Pitman Jan 26 '10 at 22:09