toddmo toddmo - 16 days ago 4
C# Question

Use linq to convert string to 3D array

I saw examples, and have implemented linq to convert a delimited string to a 2D array like so:

using System;
using System.Linq;

namespace AACOBusinessModel.Extensions
{
[Serializable]
public class TwoDimensionalStringArray
{
public TwoDimensionalStringArray(string data)
{
// 1;2;3^^4;5;6
this.Data = (
from string line
in data.Split(new string[] { "^^" }, StringSplitOptions.RemoveEmptyEntries)
select line.Split(';')
).ToArray();
}

public TwoDimensionalStringArray() { }

public readonly string[][] Data = { };

public override string ToString()
{
return string.Join("^^",
from string[] line
in Data
select string.Join(";", line)
);
}
}
}


When I tried to make this work in 3D I ran into an issue:

using System;
using System.Linq;

namespace AACOBusinessModel.Extensions
{
[Serializable]
public class ThreeDimensionalStringArray
{
public ThreeDimensionalStringArray(string data)
{
// 1;2;3^^4;5;6@4;4;4^^7;7;7
this.Data = (
from string line2D
in data.Split(new string[] { "@" }, StringSplitOptions.RemoveEmptyEntries)
from string line
in line2D.Split(new string[] { "^^" }, StringSplitOptions.RemoveEmptyEntries)
select line.Split(';')
);
}

public ThreeDimensionalStringArray() { }

public readonly string[][][] Data = { };

public override string ToString()
{
return string.Join("@",
from string[][] line2D
in Data
select string.Join("^^",
from string[] line
in line2D
select string.Join(";", line)
)
);
}
}
}


I understand that with 2D the ending select was a collection of splits converted to an array thus making a 2D array.

But with 3D, the ending select needs to select a collection of 2D arrays. I don't know how to do this.

UPDATE

I came up with this but I'd like the query syntax if it's possible.

public ThreeDimensionalStringArray(string data)
{
this.Data = (
from string line2D
in data.Split(new string[] { "@" }, StringSplitOptions.RemoveEmptyEntries)
select (
from string line
in line2D.Split(new string[] { "^^" }, StringSplitOptions.RemoveEmptyEntries)
select line.Split(';')
).ToArray()
).ToArray();
}

Answer

Not sure how this should be done in query syntax, but here is the method syntax version:

this.Data = data
    .Split(new[] { "@" }, StringSplitOptions.RemoveEmptyEntries)
    .Select(table => table.Split(new[] { "^^" }, StringSplitOptions.RemoveEmptyEntries)
        .Select(row => row.Split(';'))
        .ToArray())
    .ToArray();

In query synax :

this.Data = (
    from table in data.Split(new[] { "@" }, StringSplitOptions.RemoveEmptyEntries)
    select
    (
        from row in table.Split(new[] { "^^" }, StringSplitOptions.RemoveEmptyEntries)
        select row.Split(';')
    ).ToArray()
).ToArray();