tags:

views:

280

answers:

3

Lets say there is an array like this:

double [] numbers = new double[] {1,1,2,2,5,7,7,7};

I want to copy only the different numbers to a new array (the result should be numbers = {1,2,5,7}) in a time efficient way. I know how to do it in a time inefficient way - by looking if the next number is the same as the one before and continuing the copy loop if they are. Is there another way?

+6  A: 
using System.Linq;

double[] newArray = numbers.Distinct().ToArray();
Chad Grant
+1, Beat me to it!
LukeH
I like this solution, but I'm not using .NET 3.5 (maybe I should start)
A: 

Obviously it is necessary to examine every element of the list to do this. The "time inefficient" way you describe is actually already a description of the bare essentials of what you'd have to do. If you want a convenient way to do it, Linq already defines the Distinct() operator, which you can then combine with ToArray().

Daniel Earwicker
+2  A: 

If you don't have Linq, you can do the following:

List<double> uniques = new List<double>;
foreach (double num in numbers)
{
  if (!uniques.Contains(num)) uniques.Add(num);
}

double[] uniquearray = uniques.ToArray();
ck
This also covers the case when the list is unordered.
ChrisF