I'm trying to create a utility method that will accept two arrays as parameters, merge them together, and return the resulting array. Discarding duplicates.
Ideally, the parameters would accept any array type, such as int[] or string[].
I'm using C# .NET 1.1, and therefore do not have access to Generics or Array.Resize().
Is there a better way to merge two arrays, without knowing their type, but returning an array of the same type?
At this time, the following code returns an array of object[]. I'd like the returned array type to match the parameters.
public static object[] MergeArrays(object[] dest, object[] src)
{
if (dest.GetType() != src.GetType())
return null; // The arrays are of different types
if (dest.Equals(src))
return dest; // Don't merge with self
// We now know there are two compatible and unique arrays
int delta = src.Length;
// Cycle through the passed materials and see if they already exist
for (int i = 0; i < src.Length; i++)
// Check to see if this material already exists
for (int j = 0; j < dest.Length; j++)
if (src[i] == dest[j])
{
// The material already exists, so we'll skip it
src[i] = null;
delta--;
break;
}
// If there are still objects to merge, increase the array size
if (delta > 0)
{
object[] = new object[dest.Length + delta];
int index;
// Copy the original array
for (index = 0; index < dest.Length; index++)
tmp[index] = dest[index];
// Add the new elements
for (int i = 0; i < src.Length; i++)
{
if (src[i] == null)
continue;
tmp[index++] = src[i];
}
dest = tmp;
}
return dest;
}