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?

3
  • What is the expected result? A input / output example would help Commented Jun 27, 2016 at 9: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 "{"" Commented Jun 27, 2016 at 9:33
  • Possible duplicate of Array of arrays, with different sizes Commented Jun 27, 2016 at 9:36

4 Answers 4

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;
}
Sign up to request clarification or add additional context in comments.

Comments

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;
}

1 Comment

Thanks, that was exactly what I was searching for! Works great.
0

Are you looking for Jagged Array ?

You can also create an Array of Arrays

Comments

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;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.