I understand this is somewhat trivial but...
What the best way to get the reference the first item of a collection if any exist? Assume the collection contains items of a reference-type.
Code Sample 1:
if (collection.Any())
{
var firstItem = collection.First();
// add logic here
}
The above sample has two separate calls on the collection starting an iteration which complete as soon as the first is detected.
Code Sample 2:
var firstItem = collection.FirstOrDefault();
if (firstItem != null)
{
// add logic here
}
The above sample only has a single call on the collection but introduces a variable that is unnecessarily in a wider scope.
Is there a best-practices related to this scenario? Is there a better solution?
I prefer the second example because it's more effecient in the general case. It's possible that this collection is combination of many different delay evaluated LINQ queries such that even getting the first element requires a non-trivial amount of work.
Imagine for example that this collection is build from the following LINQ query
var collection = originalList.OrderBy(someComparingFunc);
Getting just the first element out of collection
requires a full sort of the contents of originalList
. This full sort will occur each time the elements of collection
are evaluated.
The first sample causes the potentially expensive collection to be evaluated twice: via the Any
and First
method. The second sample only evaluates the collection once and hence I would choose it over the first.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With