In .NET, if you want to get the first item from an IList object, you could just use the index: list[0]. You also have a handy-dandy function called First, or even better FirstOrDefault. FirstOrDefault helpfully doesn’t throw an exception if the list is empty (though depending on what’s in the list, it may give you a null).

What I’m saying is that there are plenty of easy, and obvious ways to get the first element of a list.

Stevie’s co-worker did this instead:

IList<Order> orderList = db.GetOrdersByDateDescending().ToList();
int i = 1;
foreach (Order order in orderList)
{
    if (i == 1)
    {
        PrintOrder(order);
    }
    i++;
}

So, for starters, GetOrdersByDateDescending() is a LINQ-to-SQL call which invokes a stored procedure. Because LINQ does all sorts of optimizations on how that SQL gets generated, if you were to do GetOrdersByDateDescending().FirstOrDefault(), it would fetch only the first row, cutting down on how much data crosses the network.

But because they did ToList, it will fetch all the rows.

And then… then they loop over the result. Every single row. But they only want the first one, so they have an if that only triggers when i == 1, which I mean, at this point, doing 1-based indexing is just there to taunt us.

Stevie adds: “This is a common ‘pattern’ throughout the project.” Well clearly, the developer responsible isn’t going to do something once when they could do it every single time.

[Advertisement] Utilize BuildMaster to release your software with confidence, at the pace your business demands. Download today!