First up, your
AddToArray
code is wrong. You copy the empty
returnarray
to the passed-in
garray
array. You then copy the empty
returnarray
to the single-element
newarray
array. Both attempts to copy will result in an
ArgumentException
:
ArgumentException:
Destination array was not long enough. Check destIndex and length, and the array's lower bounds.
You need to reverse the direction of your copy operation. And you can simplify your code while you're at it:
private T[] AddToArray<T>(T[] garray, T objg)
{
Array.Resize(ref garray, garray.Length + 1);
garray[garray.Length - 1] = objg;
return garray;
}
The
Array.Resize[
^] method takes care of allocating a new array of the desired size and copying the values from the old array to the new array.
For the
Distinct
method, I'd suggest something like this:
private T[] Distinct(T[] ourarray)
{
if (ourarray is null || ourarray.Length == 0)
{
return ourarray;
}
HashSet<T> distinctValues = new HashSet<T>();
bool[] itemsToRemove = new bool[ourarray.Length];
int numberOfItemsToRemove = 0;
for (int index = 0; index < ourarray.Length; ++index)
{
if (distinctValues.Add(ourarray[index])) continue;
itemsToRemove[index] = true;
++numberOfItemsToRemove;
}
if (numberOfItemsToRemove == 0)
{
return ourarray;
}
int resultLength = ourarray.Length - numberOfItemsToRemove;
T[] result = new T[resultLength];
int resultIndex = 0;
for (int index = 0; index < ourarray.Length; index++)
{
if (itemsToRemove[index]) continue;
result[resultIndex] = ourarray[index];
++resultIndex;
}
return result;
}
If the version of the .NET Framework you're using doesn't support the
HashSet<T>
type, then it's seriously out-of-date. That class has been around since .NET Framework 3.5, released back in 2007.