简体   繁体   中英

Linq FirstOrDefault(<condition>).Attribute vs Where(<condition>).Select(a => Attribute).FirstOrDefault()

I've been cleaning up some old code and came accross a few queries of the following structure:

var attribute = DbSet.Where(<condition>).Select(a => a.Attribute).SingleOrDefault();

and as I'm trying to make the code more readable I would change that to:

var attribute = DbSet.SingleOrDefault(<condition>).Attribute;

therefore shortening the statement.

But now I'm wondering which of the two is better for performance, and which is better for memory management.

It depends. DbSet.SingleOrDefault(<condition>).Attribute will fetch whole row from database and pass it over the network to you application. So if your table has many columns and/or columns containing a lot of data (big stings, some binary data) then first one should be faster cause it will fetch only data which is actually needed.

Also note that SingleOrDefault can return null, so without null check you can get NullReferenceException .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM