Matthew Cox Team : Web Development Tags : Web Development

Using the .Any() linq extension

Matthew Cox Team : Web Development Tags : Web Development

Whilst hunting down performance issues on one of our websites, I came across a number of linq statements that were contributing to the issue.

Ordinarily when working with a set of values – be it a list or an array – we usually check for the variable being null or empty before utilising it.  Whilst .count is fine for lists and .length is fine for arrays, when working with linq, all our values are IQueryables or IEnumerables which have neither length or count properties.

The logical substitution for these properties is to call the .Count() linq extension method, but if you take a second to think about it, this is actually really bad practice. We’re querying a table that could potentially have thousands of rows, and all we want to know is if there is one or more records in my result set. Instead, we’re getting the server to go through and load every single record in the result set to find out if it’s empty – that is incredibly inefficient.

Instead, we should be using the .Any() linq extension method. This method returns a Boolean value indicating if there are any records in the result set and it will only ever read the first record.

No more performance issues!