LinQ: Max() vs OrderBy()-FirstOrDefault()

What about this:

var i = (from item in listOfItems
select item).Max();

And what about if listOfItems is empty ?
Max() throws an exceptions, then you change to:

var i = (from item in listOfItems
order by item descending
select item).FirstOrDefault();

but, the last statement has higher cpu usage.

Jon Skeet in A short case study in LINQ efficiency made a performance test very interesting.

Technorati tags: LinQ


2 Responses to “LinQ: Max() vs OrderBy()-FirstOrDefault()”

  1. ivowiblo Says:

    Maybe you could add a new extension method:

    public static T MaxOrDefault( this IEnumerable self){
    if( self.Count() == 0 )
    return default(TReturn);

    return self.Max();

    I know, it uses Count() and you don’t know what it will be doing there but for sure you can change the implementation in the future if you need it.

  2. Exploring LinQ « a developer’s breadcrumb Says:

    […] to my last post (LinQ: Max() vs OrderBy()-FirstOrDefault()) here is a similar example: var i = (from item in listOfItems where item.Size = listOfItems.Max(i […]

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: