Search code examples
c#.netcsvaveragetextfieldparser

Reading numbers from CSV file and calculating the average


I need help taking numbers from a CSV file and calculating the average. So far I can retrieve the correct numbers from the last column, but it seems like I am not converting them to right type of array. I think the number I am looking for should be Average = 6.4.

private void label21_Click(object sender, EventArgs e)
{
    var path = conf.path + "\\" + "CloudOpen.csv"; 

    using (TextFieldParser csvParser = new TextFieldParser(path))
    {
        csvParser.CommentTokens = new string[] { "#" };
        csvParser.SetDelimiters(new string[] { "," });
        csvParser.HasFieldsEnclosedInQuotes = false;
        csvParser.ReadLine();

        while (!csvParser.EndOfData)
        {
            // Read current line fields, pointer moves to the next line.
            string[] fields = csvParser.ReadFields();
            string five = fields[5]; 
            var intArray = five.Select(c => c - '0').ToArray(); 

            Average(intArray);
        }
    }
}

public void Average(int[] array)
{
    double avg = Queryable.Average(array.AsQueryable());

    Console.WriteLine("Average = " + avg);
}

Here is the CSV file I am reading:

Id,time,two,five,ten,twenty
0,03/07/2022 14:47:03,0,1,2,5
0,03/07/2022 14:47:33,0,1,2,6
0,03/07/2022 14:48:37,0,1,3,6
0,03/07/2022 14:48:37,0,1,3,6
0,03/07/2022 14:48:37,0,1,3,7
0,03/07/2022 14:48:37,0,1,3,8

Solution

  • public void average()
    
            {
    
                List<double> listA = new List<double>();
    
                int five;
    
                var path = conf.path + "\\" + "CloudOpen.csv"; 
    
                using (TextFieldParser csvParser = new TextFieldParser(path))
    
                {
    
                    csvParser.CommentTokens = new string[] { "#" };
    
                    csvParser.SetDelimiters(new string[] { "," });
    
                    csvParser.HasFieldsEnclosedInQuotes = false;
    
                    csvParser.ReadLine();
    
                    while (!csvParser.EndOfData)
    
                    {
                        string[] fields = csvParser.ReadFields();
    
                        five = fields[5].Count();
       
                        var fi = Convert.ToInt32(fields[5]);
    
                        listA.Add(fi);
    
                    }
    
                    int total = listA.Sum(x => Convert.ToInt32(x));
    
                    var count = listA.Count;
    
                    Console.WriteLine("Numbers added:" + total);
    
                    Console.WriteLine("Number of items:" + listA.Count);
    
                    Console.WriteLine(total / count);
    
                }
    
            }