4
\$\begingroup\$

Is this the best way to do this sort?

assets.OrderBy(a =>
    a.GalleryItems != null &&
    a.GalleryItems.FirstOrDefault() != null
        ? a.GalleryItems.OrderBy(gi => gi.SortOrder).First().SortOrder
        : 1000)

Basically I have a group of assets, which contain a group of gallery items with a sort order. I need to get the lowest sort order from this group and sort the assets by that. Gallery items can be null (it is coming through a service so I am unable to change this).

\$\endgroup\$

closed as off-topic by t3chb0t, IEatBagels, Sᴀᴍ Onᴇᴌᴀ, Toby Speight, Ludisposed Feb 28 at 14:40

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Lacks concrete context: Code Review requires concrete code from a project, with sufficient context for reviewers to understand how that code is used. Pseudocode, stub code, hypothetical code, obfuscated code, and generic best practices are outside the scope of this site." – t3chb0t, IEatBagels, Sᴀᴍ Onᴇᴌᴀ, Toby Speight, Ludisposed
If this question can be reworded to fit the rules in the help center, please edit the question.

4
\$\begingroup\$

What about something like this:

assets.OrderBy(a => a.GalleryItems != null && 
                    a.GalleryItems.Any()
                    ? a.GalleryItems.Min(gi => gi.SortOrder) 
                    : 1000)

It's actually a bit faster, since sorting the inner list takes longer than just getting the minimum value.

\$\endgroup\$
  • \$\begingroup\$ I like the use of min, think that's what I was after. Looks a lot neater \$\endgroup\$ – Pete Apr 7 '14 at 14:32

Not the answer you're looking for? Browse other questions tagged or ask your own question.