Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort objects by string propery, empty string last

I have an array of objects which all contain string property. I want to sort objects by string property alphabetically in a way that objects with empty string property come at the end of the list. Currently I have this:

switches = switches.OrderBy(n => n.GetCurrentUser()).ToArray();

The problem is that it puts empty strings at the top of the list. How do I put objects with strings with value (sorted alphabetically) at the top and objects with empty strings at the bottom?

like image 299
Aleks Vujic Avatar asked Jun 28 '26 04:06

Aleks Vujic


2 Answers

You can use:

switches = switches
    .Select(n => new { TheObject = n, User = n.GetCurrentUser() })
    .OrderBy(x => String.IsNullOrEmpty(x.User) ? 1 : 0)
    .ThenBy(x => x.User)
    .Select(x => x.TheObject)
    .ToArray();

This will first build two groups, the one with empty user and others. OrderBy will move them to the end because 1 is more than 0. If you want them at the top use OrderByDescending.

Then i use ThenBy to sort alphabetically which will only matter for the non-empty users.

like image 60
Tim Schmelter Avatar answered Jun 30 '26 18:06

Tim Schmelter


You can also use inline Comparer creation:

switches.OrderBy(n => n.GetCurrentUser(),                
                Comparer<string>.Create((a, b) =>
                string.IsNullOrEmpty(a) && !string.IsNullOrEmpty(b)? 1 
                : !string.IsNullOrEmpty(a) && string.IsNullOrEmpty(b) ? -1 
                : string.Compare(a, b)));
like image 40
Access Denied Avatar answered Jun 30 '26 17:06

Access Denied