Check if linq object is referenced

70 Views Asked by At

What is the best (fastest) way to check if a linq object is referenced from another table. Normaly i do this way but i guess this might be slow on bigger tables.

CurrentObject.ReferencingObjects.Count != 0

This might be faster.

CurrentObject.ReferencingObjects.FirstOrDefault() != null

Is there a better way?

1

There are 1 best solutions below

0
On BEST ANSWER

If ReferencingObjects implements ICollection<T> (which it appears to, given that it has a Count property), the first option is likely actually faster, as Count (for most implementations) is often stored directly, so this effectively is just a property looking up a field directly.

If, however, you were using Enumerable.Count() (the method, not a property), then my preferred method would instead be to use:

CurrentObject.ReferencingObjects.Any();

As the Any() method is very clearly showing your intent, and also very quick in general.