Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to check and retrieve the first item of a collection?

Tags:

scope

c#

linq

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?

like image 329
Luke Baulch Avatar asked Mar 02 '11 00:03

Luke Baulch


1 Answers

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.

like image 111
JaredPar Avatar answered Sep 19 '22 16:09

JaredPar