---
title: "How to convert jagged array to 2D array?"  
description: "How to convert jagged array to 2D array?"  
author: "Royce Roy"  
published: 2013-12-17  
updated: 2013-12-17  
canonical: https://www.mindstick.com/forum/1796/how-to-convert-jagged-array-to-2d-array  
category: "c#"  
tags: ["c#"]  
reading_time: 2 minutes  

---

# How to convert jagged array to 2D array?

I have a [file](https://www.mindstick.com/articles/59/encrypting-and-decrypting-files-using-c-sharp) file.txt with the following:

6,73,6,71

32,1,0,12

3,11,1,134

43,15,43,6

55,0,4,12

And this [code](https://yourviews.mindstick.com/view/85458/alan-turing-the-mastermind-behind-cracking-the-enigma-code-during-world-war-ii) to read it and [feed](https://www.mindstick.com/forum/156326/what-is-rss-feed) it to a [jagged array](https://www.mindstick.com/articles/335/jagged-array-in-c-sharp-dot-net):

```
    string[][] arr =new string[5][];    string[] filelines= File.ReadAllLines("file.txt");    for (int i = 0; i< filelines.Length; i++)     {        arr[i] =filelines[i].Split(',').ToArray();    }
```

How would I do the same thing, but with a 2D array?

## Replies

### Reply by Pravesh Singh

Hi Royce,

\
Assuming you know the dimensions of your 2D array (or at least the maximum dimensions) before you start reading the file, you can do something like this:

string[,] arr = new string[5,4];

```
string[] filelines = File.ReadAllLines("file.txt");
for (int i = 0; i < filelines.Length; i++){
    var parts = filelines[i].Split(','); // Note: no need for .ToArray()
    for (int j = 0; j < parts.Length; j++)
    {
        arr[i, j] = parts[j];
    }
}
```

If you don't know the dimensions, or if the number of integers on each line may vary, your current code will work, and you can use a little Linq to convert the array after you've read it all in:

\

\

```
string[] filelines = File.ReadAllLines("file.txt");string[][] arr = new string[filelines.Length][];for (int i = 0; i < filelines.Length; i++){    arr[i] = filelines[i].Split(',');       // Note: no need for .ToArray()}// now convertstring[,] arr2 = new string[arr.Length, arr.Max(x => x.Length)];for(var i = 0; i < arr.Length; i++){    for(var j = 0; j < arr[j].Length; j++)    {        arr2[i, j] = arr[i][j];    }}
```

Thanks


---

Original Source: https://www.mindstick.com/forum/1796/how-to-convert-jagged-array-to-2d-array

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
