Search code examples
c#csvstreamreader

C#, Read CSV for repeated cell values in 2 columns, count how many times something appears, add 1 to it and append it to a string for number increment


Basically, I have a friendly name generator that consist of Project Name_Project Build_, and a number at the end indicating that its for example 3rd of 3 total of same project and build. Example: This is what I have in CSV File: the number at the end keeps incrementing counting rows +1. enter image description here Project Name, Project Build
Toyota, 2007
Toyota, 2007

Friendly name = Toyota_2007_01 > where 1 indicates that Toyota and 2007 only appears once in same row. Adding 1 more Toyota 2007, would generate a friendly name: Toyota_2007_02 where 02 indicates that there are 2 of same Toyota 2007 in the csv so if I add next, it will append 03 for the 3rd entry

This is what the csv should have now:

(csv Header)

Project Name, Project Build, Friendly Name.

Toyota, 2007, Toyota_2007_01.

Toyota, 2007, Toyota_2007_02

If I add a different project in the same csv in the next available row,

Honda 2009

than code should find that Honda and 2009 in "same row" only appears once so friendly name should be Honda_2009_01....

My code already generates the friendly name up to "build year" but I want it to actually go in the csv, read it and find how may time project name and build year appear in same row and count, than add 1 to append that number at the end depending on how many of those things are in the file.

Here is the Code so far.

some code above... { // counting lines in CSV file // This method counts the number of Rows in the File skipping over the header row assigns value to variable, increments by 1 for next entry

        using (StreamWriter sw = new StreamWriter(path, true)) // true for appending data to file, false to overwrite in file
        {
            if (headerLine)
            {
                sw.WriteLine(header);
                sw.WriteLine(string.Format(projectName + "," + projetcBuild.ToString() + "," + projectSN.ToString()));
            }
            else if (File.Exists(path))
            {
                sw.WriteLine(string.Format(projectName + "," + projetcBuild.ToString() + "," + projectSN.ToString()));
            }
            
        }



        int counter = 0;
        string line;

        StreamReader file = new StreamReader(@"C:\LOG.csv");
        string headerLine = file.ReadLine();
        while ((line = file.ReadLine()) != null)
        {
            counter++;
        }
        string FreindlyName = ProjectName_TextBox.Text + "_" + ProjectBuild_TextBox.Text + "_" + counter;
        file.Close();

The CSV should have, this

enter image description here

I hope I did not over explain this. Thanks in advance.


Solution

  • First, I noticed your counter is totally wrong. I just fixed your counter hope this can solve your problem.

        string line;
        StreamReader file = new StreamReader(@"C:\LOG.csv");
        string headerLine = file.ReadLine() ;
        
        var counter = new List<string>();
        while (!string.IsNullOrWhiteSpace( (line = file.ReadLine()) ))
        {
            var cells = line.Split(','); // use your seprator => ,  |
            var projectFullName = $"{cells[0]}_{cells[1]}"; // eg Toyota_2007
            counter.Add(projectFullName);
        }
        var newName = ProjectName_TextBox.Text + "_" + ProjectBuild_TextBox.Text
        var newCount = counter.Where(q=> q == newName).Count() + 1;
    
        string freindlyName = $"{newName}_{newCount.ToString("00")}"; // freindlyName with correct number
        file.Close();
    

    UPDATE:

    A better counter.

    just add this function to your code and use it to get correct count of your records.

    public int CountFromLogFile(string projectName, string projectBuild, char seprator ,string csvPath)
    {
        var isHeader = true;
        var counterDic = new Dictionary<string,int>();
        foreach (var line in File.ReadLines(csvPath))
        {
            if (isHeader)
            {
                isHeader = false;
                continue;
            }
            var cells = line.Split(seprator); // 0 => projectName & 1 => projectBuild
            var fName = $"{cells[0]}_{cells[1]}";
            if (counterDic.ContainsKey(fName))
                counterDic[fName]++;
            else
                counterDic.Add(fName,0);
        }
        var qName = $"{projectName}_{projectBuild}";
        return counterDic.ContainsKey(qName) ? counterDic[qName] : 0 ;
    }
    
    

    Usage:

    var count = CountFromLogFile(ProjectName_TextBox.Text , ProjectBuild_TextBox.Text , ',' , @"C:\LOG.csv");