Answer the question
In order to leave comments, you need to log in
How to glue several subarrays located in one array of type Object?
The task is as follows: there is a function that accepts an array of type Object with an unlimited number of elements as input. Array elements must be arrays of any type. I need to glue these same arrays into one, but on the condition that the transferred arrays have the same data types, otherwise I need to output null . I have already implemented a check for the same data types of arrays, rather clumsily, but it doesn’t matter, the question is different: I can’t glue the transferred arrays into one. Here is my code:
static Array Combine(params Object[] array)
{
List<Type> types = Type.GetTypeArray(array).OrderBy(x => x.Name).ToList(); //отсортированный список типов данных элементов
List<Type> typesWithoutDublicates = new List<Type>(); //список тех же типов но без дубликатов
for (int i = 0; i < types.Count - 1; i++)
if (types[i] != types[i + 1])
typesWithoutDublicates.Add(types[i]);
if (typesWithoutDublicates.Count > 0) //если элементов больше нуля значит типы не совпадают
return null;
//требуется помощь в этом участке кода:
Array resultArray = Array.CreateInstance(array.GetType().GetElementType(), array.Length); //создание массива
Array.Copy(array, resultArray, array.Length);
return resultArray;
}
public static void Main()
{
var ints = new[] { 1, 2 };
var strings = new[] { "A", "B" };
Print(Combine(ints, ints, ints));
Print(Combine(ints));
Print(Combine());
Print(Combine(strings, strings));
Print(Combine(ints, strings));
Print(Combine(ints, ints));
}
static void Print(Array array)
{
if (array == null)
{
Console.WriteLine("null");
return;
}
for (int i = 0; i < array.Length; i++)
Console.Write("{0} ", array.GetValue(i));
Console.WriteLine();
}
Answer the question
In order to leave comments, you need to log in
DEL (first solution was wrong)
UPD:
private static Array Combine(params object[] arrays)
{
if (arrays.Length == 0) return null;
if (arrays.Length == 1) return (Array)arrays[0];
var totalLength = ((Array)arrays[0]).Length;
var elemType = arrays[0].GetType().GetElementType();
for (int i = 1; i < arrays.Length; i++)
{
var nextElemType = arrays[i].GetType().GetElementType();
if (nextElemType != elemType) return null;
totalLength += ((Array)arrays[i]).Length;
}
Array resultArray = Array.CreateInstance(elemType, totalLength);
var offset = 0;
foreach (Array array in arrays)
{
Array.Copy(array, 0, resultArray, offset, array.Length);
offset += array.Length;
}
return resultArray;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question