tags:

views:

558

answers:

2

Hi,

How do I split a string into a multidimensional array or a jagged array without looping? I saw a code snippet where someone was doing so with a file stream and I can't figure out how to make it work for my string. My string is similar to 1:2;3:1;4:1 and can be split into ID:Qty. Here is the code I saw:

string[][] lines = File.ReadAllLines(path)
    .Select(line => line.Split(',').ToArray()).ToArray();

Thanks in advance.

+2  A: 
MyString.Split(';').Select(s => s.Split(':'))

That will give you an IEnumerable<IEnumerable<string>>. You can call .ToArray() if you really want to, but it's rarely worth it.

Joel Coehoorn
Your answer is good. It leaves me one step short of completion - how do I get from <IEnumerable<IEnumerable<string>> to String[][]?
Praesagus
Do you really need a string[][]? IEnumerable will do 90% of what you need, and converting to a real array before you need to is very bad for performance. If you do, the only change you need to make is calling `.ToArray()` in the right places. You might also consider if you could get by with an array of IEnumerable or an IEnumerable of arrays.
Joel Coehoorn
+2  A: 
String s = "1:2;1:3;1:4";
String[][] f = s.Split( ';' ).Select( t => t.Split( ':' ) ).ToArray();
Philip Davis
You are awesome, thanks.
Praesagus