How can I count the unique numbers in an array without rearranging the array elements?


Question

I am having trouble counting the unique values in an array, and I need to do so without rearranging the array elements.

How can I accomplish this?

1
8
9/26/2012 7:51:25 AM

If you have .NET 3.5 you can easily achieve this with LINQ via:

int numberOfElements = myArray.Distinct().Count();

Non LINQ:

List<int> uniqueValues = new List<int>();
for(int i = 0; i < myArray.Length; ++i)
{
    if(!uniqueValues.Contains(myArray[i]))
        uniqueValues.Add(myArray[i]);
}
int numberOfElements = uniqueValues.Count;
16
3/5/2009 5:38:01 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon