0

I'm trying this:

  object [,] objArray = MySQLConn.MyRecordSet.GetRows()
  string[] NewArray = Enumerable.SelectMany(objArray, 2).ToArray();

To get the 2nd dimension's values in the object array in to a 1D string array - Where do I specify the 2nd dimension?

jamheadart
  • 5,047
  • 4
  • 32
  • 63
  • 1
    So the question is how to flatten C# arrays?. If so, LINQ's `Enumerable.SelectMany` could do that – Freggar May 11 '18 at 13:04
  • I suppose so, but I'm not sure how to apply this straight in to a new array declared by `string NewArray[] = ...` I'm trying things like `string NewArray[] = objArray.SelectMany...` but it's not compiling at all, I have no idea where to declare the 2nd dimension, or trying `SelectMany(objArray(1), NewArray)` - haven't got a clue really. – jamheadart May 11 '18 at 13:38
  • 1
    Maybe something like `string[] NewArray = objArray.SelectMany((o) => o).Cast().ToArray();` would work? – Freggar May 11 '18 at 13:48
  • 1
    Aso define the Array as `object[][] objArray` if possible – Freggar May 11 '18 at 13:49
  • Ok I was getting closer with my latest edit - what is the (o) variable?! I've got `string[] arraySQL = Enumerable.SelectMany((o) => o).Cast.ToArray();` but it says "No overload for SelectMany takes 1 arguments` – jamheadart May 11 '18 at 13:52
  • And setting my array as [][] doesn't work when I pull it from a recordset :( so I have to use [,] – jamheadart May 11 '18 at 13:58
  • Ok seems I'm just adding confusion instead of helping. I hadn't used ADO for ages so I was not sure if that stuff would work. The easiest solution would honestly be to just loop through the 2D-Array, cast the elements to string and append it to a list – Freggar May 11 '18 at 14:03
  • https://stackoverflow.com/questions/5132397/fast-way-to-convert-a-two-dimensional-array-to-a-list-one-dimensional maybe helps – Freggar May 11 '18 at 14:07

1 Answers1

0

If you don't care about the first dimension values and you're just trying to retrieve and flatten the second dimension values you can just do this:

string[] secondDimensionStrings = array.Select(item => item[1].ToString()).ToArray();

You could cast instead but I'm not sure if you're trying to convert to strings from some other type or if you're just casting down.

You can try it live here: https://dotnetfiddle.net/m6SNCP

S.C.
  • 1,152
  • 8
  • 13
  • I found out just before I left work that I need to convert from decimals actually. I will try this soon and let you know if it works, sounds ideal though! – jamheadart May 11 '18 at 15:52