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.
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.
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 ...
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.
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.
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);
How about
return foo.OrderBy(foo => foo.DisplayOrder == 0 ? int32.MaxValue : foo.DisplayOrder);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With