Which LINQ statement is better and why?

c#, linq, linq-to-sql

Solution

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.

Problem

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.

Original source

Related problems