This is a follow up question to Getting specific row and column value in .csv file in c# .
I have a bunch of .csv-files in a specific folder that I want to be able to re
You could have a class like this that has a _dictionary field of the type you can see in the below example, then you extract the data from a file, store them in an NxM array of strings and then you call PopulateDictionary method to add the data to the _dictionary field. You repeat this process for each file. You can then call method to read the values from the _dictionary field.
class Program
{
static Dictionary<string, Dictionary<int, Dictionary<int, double>>> _dictionary =
new Dictionary<string, Dictionary<int, Dictionary<int, double>>>();
static void PopulateDictionary(string filename, string[][] data)
{
_dictionary.Add(filename, new Dictionary<int, Dictionary<int, double>>());
for (int i = 0; i < data.Length; i++)
{
_dictionary[filename].Add(i, new Dictionary<int, double>());
for (int j = 0; j < data[i].Length; j++)
{
_dictionary[filename][i].Add(j, double.Parse(data[i][j]));
}
}
}
static double GetVal(string filename, int row, int column)
{
return _dictionary[filename][row][column];
}
static void Main(string[] args)
{
List<string> csvData1 = new List<string>() { "23, 5, 7", "40, 15" };
List<string> csvData2 = new List<string>() { "40, 80, 112", "13", "20, 65, 9" };
string[][] dataArr1 = csvData1.Select(x => x.Split(',')).ToArray();
string[][] dataArr2 = csvData2.Select(x => x.Split(',')).ToArray();
PopulateDictionary("f1", dataArr1);
PopulateDictionary("f2", dataArr2);
Console.WriteLine(GetVal("f1", 0, 0));
Console.WriteLine(GetVal("f2", 1, 0));
Console.WriteLine(GetVal("f2", 2, 2));
Console.ReadKey();
}
}
I've included a Main method for simulating the creation of a dictionary that you can easily run to check if my solution suits your needs. The lists represent the lines you should read from the csv files. The matrixes of string represent the data organized by rows and columns that contain the double values in string representation. Then, I simulate the adding of the values to the dictionary giving the filename (you should use the name of the csv files from which you extract the data) and the matrix representing the rows and the columns. At the end I read the first value found at the first column of the first row in the first list, then the single element at the unique column of the second row in the second list and at last the last column of the last row in the second list.