Is there a better way to do this linq sort? I have the following linq statement that is ordering a list of assets by the sort order of a child item:

 Assets.OrderBy(a =&gt; a.GalleryItems != null &amp;&amp;
                a.GalleryItems.FirstOrDefault(gi =&gt; gi.ProductItemCode == productId) != null
                     ? a.GalleryItems.FirstOrDefault(gi =&gt; gi.ProductItemCode == productId).SortOrder : 1000);


I was wondering if there was a more efficient way to do this as I would have thought having to do 2 a.GalleryItems.FirstOrDefault(gi =&gt; gi.ProductItemCode == productId) would be pretty poor for performance
You're correct, it can be costly.

You can just expand the lambda expression:

Assets.OrderBy(a =&gt; {
    var item = a.GalleryItems != null 
               ? a.GalleryItems.FirstOrDefault(gi =&gt; gi.ProductItemCode == productId)
               : null;
    return item != null ? item.SortOrder : 1000;
});


[Quick edit]

The above will work correctly only for LINQ 2 Objects queries.

If you're using EF or any other LINQ database provider, you should leave the query as-is, because it will probably be translated to ISNULL(..., 1000) or something equivalent.