0

The string looks like this:

"c,c,c,c,c,c\r\nc,c,c,c,c,c\r\n.....c,c,c,c,c\r\n"

This line works:

IEnumerable<string[]> lineFields = File.ReadAllLines(sFile).Select(line => line.Split(','));
List<string[]> lLines = lineFields.ToList();

But let's say I'm not reading from a file, and instead of it I have the string i described before.

What's the fastest (I refer to preformance) way to convert it to a List<> of string[] that looks like

List<string[]> lLines = [ [c,c,c,c,c] , [c,c,c,c,c] , ... [c,c,c,c,c] ]

Thanks.

Felipe Oriani
  • 37,948
  • 19
  • 131
  • 194
Mockingbird
  • 1,023
  • 9
  • 17
  • 1
    I think you allready use the fastet way with split. – CodeTherapist Jan 02 '14 at 10:43
  • Asking for the fastest way to do that may not give the results you expect, as performance will depend on the length of the string, among other things. Are you prepared to benchmark the code in all the answers you will receive? – Frédéric Hamidi Jan 02 '14 at 10:44
  • Use some benchmark. Use `System.Diagnostics.StopWatch` to measure. – Kami Jan 02 '14 at 10:45

3 Answers3

3

Something like this should work:

var list = "c,c,c,c,c,c\r\nc,c,c,c,c,c\r\n.....c,c,c,c,c\r\n"
    .Split('\n')
    .Select(s => s.Trim().Split(','));
Dave Bish
  • 19,263
  • 7
  • 46
  • 63
1

Try something like this:

// replace \r\n to ; and split it... it will be your lines
var lines = text.replace("\r\n", ";").Split(';');

// split every item of the line arrays by , and get an new array to each item
List<string[]> arrays = lines.Select(x => x.Split(',')).ToList();
Felipe Oriani
  • 37,948
  • 19
  • 131
  • 194
  • works like a charm! thanks! BTW, is there anyway to skip the replace line in order to improve performance? – Mockingbird Jan 02 '14 at 10:50
  • Doing a replace like this will be way slower on large data-set - as you'll have to create & assign a whole string in-memory of the initial string - albeit with the replaced chars. So - if a 100meg initial string - this will require at least 200meg to process. – Dave Bish Jan 02 '14 at 10:57
-1

try this

string combindedString = string.Join( ",", myList );
Carlos Landeras
  • 11,025
  • 11
  • 56
  • 82
Yanshof
  • 9,659
  • 21
  • 95
  • 195