0

I am looking for an efficient and nice way to fill an array with arrays in different sizes. I am thinking of a solution like:

private bool arrayMaking(int[] array1, int[] array2, int value, out int[] arrays)
{
    arrays = {array1, array2, value};
    return true;
}

Is there a possible solution or do I need to loop?

Draken
  • 3,134
  • 13
  • 34
  • 54
shup
  • 120
  • 1
  • 16
  • What is the expected result? A input / output example would help – fubo Jun 27 '16 at 09:30
  • oh sorry, my original method is much more complex and I tried to break it down to the essential part. The return `bool` is not relevant for the array filling process, the method can be void, too. In my Method I check, if the values in `array1` and `array2` are okay. If yes, I return the solution shown, if not, I try to change the values of array2 and after the adaption I fill the `arrays` with `{array1, array2, value}`. If the adaption is not possible, I return false. The code posted throws an error in Visual Studio, saying "Invalid Expression "{"" – shup Jun 27 '16 at 09:33
  • Possible duplicate of [Array of arrays, with different sizes](http://stackoverflow.com/questions/22745750/array-of-arrays-with-different-sizes) – Abdul Jun 27 '16 at 09:36

4 Answers4

1

If you want to initialize the array from the two other arrays and the int, you could use:

private bool ArrayMaking(int[] array1, int[] array2, int value, out int[] arrays)
{
    int size = array1.Length + array2.Length + 1;
    arrays = new int[size];
    for (int i = 0; i < array1.Length; i++)
        arrays[i] = array1[i];
    for (int i = 0; i < array2.Length; i++)
        arrays[i + array1.Length] = array2[i];
    arrays[arrays.Length - 1] = value;
    return true;
}

less efficient but more readable using LINQ:

private bool ArrayMaking(int[] array1, int[] array2, int value, out int[] arrays)
{
    arrays = array1.Concat(array2).Concat(new[] {value}).ToArray();
    return true;
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
0

Are you looking for Jagged Array ?

You can also create an Array of Arrays

Community
  • 1
  • 1
Abdul
  • 2,002
  • 7
  • 31
  • 65
0

It sounds to me that you want to merge one or more arrays into single Array. You could do this using Concat (or Union to eliminate duplicates).

private bool arrayMaking(int[] array1, int[] array2, int value, out int[] arrays)
{
    arrays = array1.Concat(array2).Concat( new int[] {value}).ToArray();
    return true;
}
Hari Prasad
  • 16,716
  • 4
  • 21
  • 35
0

You could use LINQ to solve your problem:

// Make sure to add these first:
using System.Linq;
using System.Collections.Generic;

private bool arrayMaking(int[] array1, int[] array2, int value, out int[] arrays)
{
    List<int> array = new List<int>();
    array.AddRange(array1);
    array.AddRange(array2);
    array.Add(value);
    arrays = array.ToArray();
    return true;
}