Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make zero appear last in a sorted list of integers

I have a list of objects and want to order them by some property

List<Foo> foo = GetList();    
return foo.OrderBy(foo => foo.DisplayOrder);

The catch is that when DisplayOrder is zero I need to place that item in last position.

My question is the same as make zero appear last in a list of ascending numbers but in C#. It's easy to solve but I want to see some creative, concise answers.

like image 567
Kirk Broadhurst Avatar asked Nov 16 '11 22:11

Kirk Broadhurst


People also ask

How to move all zero’s to the end of an array?

Move all zeroes to end of array. Given an array of random numbers, Push all the zero’s of a given array to the end of the array. For example, if the given arrays is {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0}, it should be changed to {1, 9, 8, 4, 2, 7, 6, 0, 0, 0, 0}. The order of all other elements should be same.

How to find first and last positions in a sorted array?

Find first and last positions of an element in a sorted array 1 For the first occurrence of a number#N#a) If (high >= low) b) Calculate mid = low + (high - low)/2; c) If ( (mid == 0... 2 For the last occurrence of a number More ...

How do you count non-zero elements in an array?

For every non-zero element arr [i], put the element at ‘arr [count]’ and increment ‘count’. After complete traversal, all non-zero elements have already been shifted to front end and ‘count’ is set as index of first 0.

How to find first and last element in a for loop?

Run a for loop and for i = 0 to n-1 2. Take first = -1 and last = -1 3. When we find element first time then we update first = i 4. We always update last=i whenever we find the element.


2 Answers

You can use the fact that you can order by a boolean value. If you first order by DisplayOrder == 0 this will results to true for all zero values and false for all other values. Since true will ordered after false all zero values will be at the very end:

return foo.OrderBy(x => x.DisplayOrder == 0)
          .ThenBy(x => x.DisplayOrder);
like image 128
BrokenGlass Avatar answered Nov 10 '22 00:11

BrokenGlass


How about

return foo.OrderBy(foo => foo.DisplayOrder == 0 ? int32.MaxValue : foo.DisplayOrder); 
like image 44
Jim Wooley Avatar answered Nov 10 '22 00:11

Jim Wooley