Amos Long
Amos Long

Reputation: 1065

Retrieving property from first item with LINQ

Is there a simpler way to write this query in Linq:

var prioritiy = db.Requirements.Where(r => r.ID == rowID).Select(r => r.Priority).First();

Upvotes: 2

Views: 1858

Answers (3)

Nate Barbettini
Nate Barbettini

Reputation: 53600

If you mean "simpler" as in "less code", your self-answer is already the most compact:

db.Requirements.First(r => r.ID == rowID).Priority;

If you mean "simpler" as in "less database overhead", then your original version is slightly better:

db.Requirements.Where(r => r.ID == rowID).Select(r => r.Priority).First();

Why? As @IvanStoev pointed out in the comments, LINQ execution is deferred until you call a "finishing" method like First(). If you're using SQL on the backend, the second example will be translated into a SQL statement that retrieves only the Priority field from the database, whereas the first example will retrieve all fields for the matching row.

This is, IMO, firmly in the realm of unnecessary micro-optimizations, unless this code runs millions of times or the full database object has tons of columns. Unless you're doing something crazy, just use the style that you like!

Upvotes: 3

Slai
Slai

Reputation: 22866

a safer version in Visual Studio 2015

var priority = db.Requirements.FirstOrDefault(r => r.ID == rowID)?.Priority;

of if you call that often, you can use a LookUp

var lookup = db.Requirements.ToLookup(r => r.ID, r => r.Priority);

var priority = lookup[rowID].FirstOrDefault();

Upvotes: 0

Amos Long
Amos Long

Reputation: 1065

Never mind. I just figured out that by applying First() initially, I return an object which contains the property I'm looking for. The code turns into:

var priority = db.Requirements.First(r => r.ID == rowID).Priority;

Upvotes: 2

Related Questions