Amos Long Amos Long - 1 year ago 73
C# Question

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();

Answer Source

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!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download