From f3b2d17b3417486946d7e3ec9a2c90d815808c5a Mon Sep 17 00:00:00 2001 From: jan00 Date: Sat, 28 Oct 2023 09:05:07 +0200 Subject: [PATCH] =?UTF-8?q?P=C5=99idejte=20soubory=20projektu.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CSVImporter.csproj | 9 +++++ Importer.cs | 89 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 98 insertions(+) create mode 100644 CSVImporter.csproj create mode 100644 Importer.cs diff --git a/CSVImporter.csproj b/CSVImporter.csproj new file mode 100644 index 0000000..132c02c --- /dev/null +++ b/CSVImporter.csproj @@ -0,0 +1,9 @@ + + + + net6.0 + enable + enable + + + diff --git a/Importer.cs b/Importer.cs new file mode 100644 index 0000000..f38a37c --- /dev/null +++ b/Importer.cs @@ -0,0 +1,89 @@ +using System.Reflection.Metadata; + +namespace CSVImporter +{ + public class Importer + { + /// + /// Import CSV data to 2D List pole + /// + /// Path of CSV File + /// Separator between values + /// Skip first x rows (do not load) + /// + public static List> ImportCSV(string path, string separator, int skip = 0) + { + List> Collumns = new List>(); //Initialize Lists Object + int RowsCount = 0; //Counting number of Rows + + foreach (string row in File.ReadAllLines(path)) //Read Lines of CSV file + { + RowsCount++; //Count Row + + if (skip < RowsCount && row.Contains(separator) && row != "") //test for skipping specified rows for skip or skip empty rows and if missing separator in row + { + List Collumn = row.Split(separator).ToList(); //Splitting CSV Line + + if (Collumns.Count < Collumn.Count) //Test if sufficient number of collumns + { + int collumnsRequest = Collumn.Count - Collumns.Count; //Count missing collumns + + while (collumnsRequest > 0) //loop for add missing collumns + { + Collumns.Add(new List(RowsCount - skip)); //Add collumn to collumns with specified number of elements + collumnsRequest--; //subtraction added collumn + } + } + + foreach (string data in Collumn) //loop for moving data to position + { + Collumns[Collumn.IndexOf(data)].Add(data); //Adding data to position + } + + if (Collumns.Count > Collumn.Count) //test if new Row is not shorter when previous + { + int missingnumber = Collumns.Count - Collumn.Count; //count missing collumns + + while(missingnumber > 0) //loop for adding empty strings to collumns in shorter row + { + Collumns[Collumn.Count + missingnumber].Add(""); //adding empty strings to collumns in shorter row + missingnumber--; //subtraction number of missing collumns data + } + } + } + } + + return Collumns; //return Imported Data + } + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + } +} \ No newline at end of file