Home > Net >  How to turn a string into a 2d string array
How to turn a string into a 2d string array

Time:02-18

as the title suggests, I am looking for guidance in how to turn a string (csvData) into a 2D string array by splitting it two times with ';' and ',' respectivly. Currently I am at the stage where I am able to split it once into rows and turn it into an array, but I cannot figure out how to instead create a 2D array where the columns divided by ',' are also separate.

string[] Sep = csvData.Split(';').Select(csvData => csvData.Replace(" ","")).Where(csvData => !string.IsNullOrEmpty(csvData)).ToArray();

I have tried various things like :

string[,] Sep = csvData.Split(';',',').Select(csvData => csvData.Replace(" ","")).Where(csvData => !string.IsNullOrEmpty(csvData)).ToArray();

naivly thinking that c# would understand what I tried to achieve, but since I am here it's obvious that I got the error that "cannot implicitly convert type string[] to string [*,*]"

Note that I have not coded for a while, so if my thinking is completely wrong and you do not understand what I am trying to convey with this question, I apologize in advance. Thanks!

CodePudding user response:

In a strongly-typed language like C#, the compiler makes no assumptions about what you intend to do with your data. You must make your intent explicit through your code. Something like this should work:

string csvData = "A,B;C,D";
string[][] sep = csvData.Split(';') // Returns string[] {"A,B","C,D"}
  .Select(str => str.Split(',')) // Returns IEnumerable<string[]> {{"A","B"},{"C","D"}}
  .ToArray(); // Returns string[][] {{"A","B"},{"C","D"}}

CodePudding user response:

Rows are separated by semicolon, columns by comma?

Splitting by ';' gives you an array of rows. Split a row by ',' gives you an array of values.

If your data has a consistent schema, as in each csv you process has the same columns, you could define a class to represent the entity to make the data easier to with with.

Let's say it's customer data:

John,Smith,8675309,[email protected];

You could make a class with those properties:

public class Customer
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Phone { get; set; }
    public string Email { get; set; }
}

Then:

var rows = csvdata.Split(';');
List<Customer> customers = new();
foreach(var row in rows)
{
    var customer = row.Split(',');
    customers.Add(new()
    {
        FirstName = row[0],
        LastName = row[1],
        Phone = row[2],
        Email = row[3]
    });
}

Now you have a list of customers to do whatever it is you do with customers.

  • Related