-2

I need to create a new bi-dimensional String array like this one:

-- Create Header and Data

 String[] Header ={"Item","Description", "Qty","Unit Price","Price"};

 String[][] data = {
     new String[]{"Spire.Doc for .NET",".NET Word Component","1","$799.00","$799.00"},
     new String[]{"Spire.XLS for .NET",".NET Excel Component","2","$799.00","$1,598.00"},
     new String[]{"Spire.Office for .NET",".NET Office Component","1","$1,899.00","$1,899.00"},
     new String[]{"Spire.PDF for .NET",".NET PDFComponent","2","$599.00","$1,198.00"},
 };

But "data" is declared on the code, the problem is that I need to declare "data" with the data (sorry about repeating "data" multiple times) of an unknown length array[n], so the code could work like:

 String[][] data = {
     new String[]{"arrayFromFunction[0].data1","arrayFromFunction[0].data2","arrayFromFunction[0].data3","arrayFromFunction[0].data4","arrayFromFunction[0].data5"},
     new String[]{"arrayFromFunction[1].data1","arrayFromFunction[1].data2","arrayFromFunction[1].data3","arrayFromFunction[1].data4","arrayFromFunction[1].data5"},
     ...
     new String[]{"arrayFromFunction[n].data1","arrayFromFunction[n].data2","arrayFromFunction[n].data3","arrayFromFunction[n].data4","arrayFromFunction[n].data5"}
};

But I don't know how to iterate INSIDE the declaration of String[][] data or how to save the iterator (n) to use it inside data declaration.

Hope I've explained well and thanks for your help.

Daniel Geyfman
  • 246
  • 1
  • 10
Gyffet
  • 17
  • 2

2 Answers2

2

So you have structured data somewhere and you want to de-structure it? That goes against any modern programming principle where you bind structured data to your view and let the framework take care of the rest.

That said, it's relatively trivial to achieve:

var data = arrayFromFunction.Select(w => new[] { w.data1, w.data2, w.data3, w.data4, w.data5 }).ToArray();
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
Blindy
  • 65,249
  • 10
  • 91
  • 131
-1

But I don't know how to iterate INSIDE the declaration of String[][] data or how to save the iterator (n) to use it inside data declaration.

You don't; this is a compile time code block you've written here. It is a constant hard baked into your program when you hit "build", with no ability to cope with your arrayFromFunction having a variable number of elements

Well..

I suppose you could write a program that generates and compiles C# on the fly

But it seems needlessly more complex than using e.g a List<string> and looping over the arrayFromFunction array and adding items to the list:

foreach(var item in arrayFromFunction)
  someList.Add(new []{ item.data1, item.data2 ... });

or writing a LINQ statement to project the arrayFromFunction to an enumerable of string arrays

var someList = arrayFromFunction.Select(item => new []{ item.data1, item.data2 ... }).ToList();
Caius Jard
  • 72,509
  • 5
  • 49
  • 80