views:

123

answers:

3

In both of the statement I am trying to fetch the ID of Catagory 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

+12  A: 

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, consistancy 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's...use them as much as you can.

Justin Niessner
+1, 17sec faster than me :-)
Fredou
Also, if there is no record with the given ID, the second will throw.
Marcel Gosselin
Thanks for the equivalent for the first one.What is equivalent for the first statement without => expression ? Thanks
Asad Butt
@asdi - Added the query syntax for the second statement.
Justin Niessner
Thanks mate, do appreciate
Asad Butt
+3  A: 

they are not the same

first one will return a list if there is many match

second one will only return one

Fredou
A: 

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:

http://stackoverflow.com/questions/630045/linq-dot-notation-vs-query-expression

Loki Stormbringer
in terms of performance as well ?
Asad Butt
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