9
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?