简体   繁体   中英

C# How do I parse a text file of data of unknown row size to a 2D array?

I can easily pass a data file to a 2D array if I know the size of the data file, but thats pretty pointless when you want to add and remove data.

How can I instantiate a 2D array of that Data rows length that is global and not out of scope to the rest of the program?

Here is the usual code, for an array of 4 rows and 6 columns, but I want to add/remove data to the data file making it of unknown length in rows.

  string[,] allStudentData = new string[4, 6];
            string[] allStudents = File.ReadAllLines("data.txt");


            for (int i = 0; i < allStudents.Count(); i++)
            {
                for (int j = 0; j < 6; j++)
                {

                    string[] DataIn = allStudents[i].Split(',');

                    allStudentData[i, j] = DataIn[j];
                }
            }

Thanks for your ideas :-)

Why not use something mutable, like a List ?

You can add columns using the .Add() command, , and you can collapse it into an array when you're done with it (.ToArray())

You can use a List that holds a custom object (it could be an array) instead of Array and then at the end convert the list to an array with the ToArray extension:

var list = new List<string[]>();
var data1 = new string[2] {"1", "2" };
var data2 = new string[3] {"1", "2", "3" };
list.Add(data1);
list.Add(data2);
list.ToArray(); // converts the list to string[][]

After you are done reading the file you could add easily more items to the list and then at the end write all modifications to the file. If you think, that in future you will need more than the two dimensional array, than it's worth it to create a custom object like:

public class Student
{
    public string Name { get; set; }
    public int Grade { get; set; }
}

and use this instead of the string[]:

var studentData = new List<Student>();

The maintenance later will be much more easier (adding address, classes, and so on). I admit, you will have a little more work to do when reading and writing, but if the project grows it will pay off.

You can still use LINQ to read the data on one line:

// creates a List<Student>
var studentData = File.ReadAllLines("data.txt")
                        .Select(row => row.Split(','))
                        .Select(elements => 
                            new Student 
                            {
                                Name = elements[0],
                                Grade = int.Parse(elements[1])
                            }).ToList();

If the number of columns is always 6 and only the number of rows is unknown. Just change the first 2 rows of your code to:

string[] allStudents = File.ReadAllLines("data.txt");
string[,] allStudentData = new string[allStudents.Count(), 6];

If the number of columns is unknown you can do this to get a 2D result :

var not2DResult = File.ReadAllLines("data.txt").Select(x => x.Split(',')).ToArray();

var maxRow = not2DResult.Count()-1;
int maxColumn = Enumerable.Select(not2DResult, c => c.Count()).Max()-1;

var result2D = new string[maxRow, maxColumn]; 
for (int rowNumber = 0; rowNumber < maxRow; rowNumber++)
{
    var row = not2DResult[rowNumber];
    for (int columnNumber = 0; columnNumber < row.Count(); columnNumber++)
    {
        result2D[rowNumber, columnNumber] = row[columnNumber];
    }
}

你可以做如下

var result = File.ReadAllLines("data.txt").Select(x=>x.Split(',')).ToArray();

Try using a Lists to hold the file information.

var myList = new List<string>();
myList = File.ReadLines("data.txt");
var my2DList = new List<List<string>>();

foreach(string line in myList)
    my2DList.Add(line.Split(','));

If you want to know the number of lines, just use:

int numberOfLines = my2DList.Count;

For the number of items in an individual line:

int lengthOfLine3 = my2DList[3].Length;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM