Click here to Skip to main content
15,900,495 members
Please Sign up or sign in to vote.
3.50/5 (2 votes)
See more:
How do you remove zeros that are in an array?
For instance if you have array[] numbers = new array[2000]
There are values in the array but some are zero. I would like to remove the zeros and return another array[]
Posted
Updated 2-Jan-12 19:00pm
v2

Here it is :

C#
public double[] RemoveZeros(double[] source)
{
    return source.Where(i => i != 0).ToArray();
}


Hope it helps.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 3-Jan-12 0:37am    
Correct, my 5, but it's good to know that working with array is ineffective if removal is used. It actually creates a new array out of old one. For more effective use System.Collections.Generic should be used.
--SA
Amir Mahfoozi 3-Jan-12 0:44am    
Absolutely I agree with you SA, and I don't use arrays since getting familiar with generic lists. :) I hope the OP see these comments.
Un_NaMeD 3-Jan-12 3:32am    
That's true.
Using an ArrayList would be much easier...
VB
dim a as integer=0
dim str as string
while a<array.length>
str=array[a]
if str=0 then 
array.delete(a)
end if
a=a+1
end while</array.length>
 
Share this answer
 
v2
Hi,

Try this without a loop.
C#
int[] a = { 1, 2, 3, 0, 7, 0 };
a = a.Where(T => T != 0).ToArray();
 
Share this answer
 
v2
Comments
Sergey Alexandrovich Kryukov 3-Jan-12 0:36am    
Don't worry about the loop, it is with the loop of course, which is in the implementation of Where.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900