Asad
Asad

Reputation: 21928

Which LINQ statement is better and why?

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.

Upvotes: 2

Views: 192

Answers (3)

Fredou
Fredou

Reputation: 20100

They are not the same.

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

The second one will only return one.

Upvotes: 3

Justin Niessner
Justin Niessner

Reputation: 245429

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.

Upvotes: 12

HitLikeAHammer
HitLikeAHammer

Reputation: 2695

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

Upvotes: 0

Related Questions