Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Trim spaces inside array (remove 0's)

Tags:

arrays

c#

trim

If I have the next array:

int[] arr = { 123, 243, 0, 0, 123, 0, 0, 0, 123 };

How can I move all the values which are not equal to 0 left as they can so the array will be built like this:

int[] arr = { 123, 243, 123, 123, 0, 0, 0, 0, 0 };

Thanks!

like image 700
Novak Avatar asked Nov 30 '22 03:11

Novak


2 Answers

How about with LINQ:

var result = arr.Where(x => x != 0).Concat(arr.Where(x => x == 0)).ToArray();

This is quite readable and has linear time complexity. On the other hand, it runs out-of-place and requires two passes over the input.

like image 68
Ani Avatar answered Dec 01 '22 17:12

Ani


OrderBy:

int[] arr = { 123, 243, 0, 0, 123, 0, 0, 0, 123 }.OrderBy(x => x == 0).ToArray();
like image 45
Scott Avatar answered Dec 01 '22 17:12

Scott