0

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

0

1 Answer 1

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.