DBoi
DBoi

Reputation: 687

Building up one array from multiple arrays in loop

I'm currently trying to build up one array by injecting multiple nested arrays into a for loop. This is not currently working but i cant figure out what i'm doing wrong.

Here is my current code :

// initialise an empty array
var x = new List<Model>();

// initialise an empty array to use in the loop
var mergedX = new List<Model>();

// Build up the array using the loop
foreach (var y in ys) {
  if (y.nestedArray != null) {
    mergedX = x.Concat(y.nestedArray).ToList();
  }
}

// Return the built up array
return mergedX;

What am I doing wrong/is there a better way to achieve this?

Thanks

Upvotes: 0

Views: 70

Answers (1)

ProgrammingLlama
ProgrammingLlama

Reputation: 38727

The problem is with this line:

mergedX = x.Concat(y.nestedArray).ToList();

You are always taking the value of x, but never changing it. Thus mergedX will only contain the final array's items.

Perhaps full LINQ would be better:

return ys
    .Where(y => y.nestedArray != null) // only take items from ys if nestedArray != null
    .SelectMany(y => y.nestedArray) // flatten the many arrays into one (in order)
    .ToList(); // materialise the result into a list

Alternatively, you can use List<T>'s AddRange method:

foreach (var y in ys)
{
    if (y.nestedArray != null)
    {
        mergedX.AddRange(y.nestedArray);
    }
}

Upvotes: 3

Related Questions