I got to this far. done with converting and everything. Now down to the other step. I want to calculate the total payments for all the employee has the same years of experiences. FOr example: 5 guys with 10 year experiences, get pay at 90k/year. I want to show all the ID of these guy with years of experiences and total payments that company pays to them.

        string[] results;
        char[] delimiter1 = new char[] { ',' };
        FileStream fStream = new FileStream("C:\\test1.txt", FileMode.Open, FileAccess.Read);
        StreamReader inFile = new StreamReader(fStream);
        string inputLine;
        inputLine = inFile.ReadLine();

        while (!inFile.EndOfStream)
        {
            inputLine = inFile.ReadLine();
            results = inputLine.Split(delimiter1, StringSplitOptions.RemoveEmptyEntries);
            string[] strings = results;
            int[] intInput = new int[strings.Length];
            for (int i = 0; i < strings.Length; i++)
            {
                Int32.TryParse(strings[i], out intInput[i]);
            }
            string empID = strings[0];
            int empClass = intInput[1];
            int empRate = intInput[2];
            double[] totalPoints = new double[30];

            if (empClass >= 1 && empClass <= 30)
            {
                totalPayments[empClass - 1] = totalPayments[empClass - 1] + empRate;
                Console.WriteLine("{0,-20} {1,-20}", empID, totalPayments[empClass - 1]);
            }
            else
            {
                Console.WriteLine("invalid years of experience");

Recommended Answers

All 7 Replies

If results is already a string array, why do you copy it to another string array?

Are ALL groups of employees with the same years of experience to be grouped together?

I was confusing, just want to read in the text file. Then calculate total payment that company has to pay for each group of employee. I copied the array to remind myself that which is which. Please help me to make it simple and short. The file under the format like below.

employee ID year experiences salary/year
EID001, 1, 90
EID002, 2, 88
EID003, 5, 99
EID004, 2, 78
EID005, 4, 100
EID006, 25, 98

I want the out put like this:

EID002 2 88
EID004 2 78
total payments for 2 employee with 2 years experiences is 166
average salary for 2 years experiences employee is 83
....

I'm just a beginer. I'm learning C# by myself so please explain it in the simpliest way :)

Thanks

I would suggest you to create a new class called "Employee", with properties: id, experiances, Salary.
Then create a generic list<T>, where T is this class name. Create new Employee on each new row read, and fill properties with data from file.
Example:

//custom class:
class Employee
{
   public string ID {get; set;}
   public int Experiance {get; set;}
   public decimal AnualSalary {get; set;}
}


//now in your code:
List<Employee> employees = new List<Employee>();
using(StreamReader sr = new StreamReader(fStream))
{
   string line;
   while((line = sr.ReadLine()) != null)
   {
       string[] data = line.Split(new char[] {','}, StringSplitOptions.RemoveEmptyEntries);
       if(data.Length == 3) //NOTE: for 3 columns only!!
       {
            Employee emp = new Employee();
            emp.ID = data[0].ToString();
            emp.Experiace = int.Parse(data[1].ToString());
            emp.AnualSalary = decimal.Parse(data[2].ToString()); 
            employees.Add8emp);
       }
   }
}

Now when youhave a list of employees, you can use Linq (queries) to get all kinds of data out (like calculate of total, or average).
Here is an example:

//calculation:
var queryTotal = employees.Select(s => s.AnualSalary).Sum();
var queryAverage = employees.Select(s => s.AnualSalary).Average();

//to read result you can do:
decimal total = queryTotal[0];
decimal average = queryAverage[0];

Hope it helps. NOTE: there might be error, I wrote the code by heart.
bye

For @Mija_Bonca only:
I like to have my custom class do a lot of the work, so I don't need to remember a lot of things about the individual object.
I also (normally) create a class as a "loader" and one as a "master". The master calls the loader and the user calls the Load method in the master.
It's confusing to explain, but it works out great.
For this example, however, I will work only with the object itself.

// My "overkill" example
using System;
using System.IO;
using System.Linq;

namespace DW_420043_CS_CON
{
   public class CEmployee
   {
      public string strID { get; set; }
      public int intExperience { get; set; }
      public decimal decAnnualSalary { get; set; }

      public CEmployee()
      {
         strID = "";
         intExperience = 0;
         decAnnualSalary = 0;
      }

      public CEmployee(CEmployee copy)
      {
         strID = copy.strID;
         intExperience = copy.intExperience;
         decAnnualSalary = copy.decAnnualSalary;
      }

      public CEmployee(string strCsvData)
      {
         int intDefault = 0;
         decimal decDefault = 0;

         string[] arr_strData = strCsvData.Split(',');
         strID = arr_strData[0];

         int.TryParse(arr_strData[1], out intDefault);
         intExperience = intDefault;

         decimal.TryParse(arr_strData[2], out decDefault);
         decAnnualSalary = decDefault;
      }

      public static bool IsValid(string strData)
      {
         if (!strData.Where(c => c.Equals(',')).Count().Equals(2))
         {  // three columns will contain two commas
            return false;
         }

         return strData.StartsWith("EID");
      }

      //////////////////////////////////////////////////////////////////////////
      // some form of these overrides are critical for making distinct objects
      public override string ToString()
      {
         return strID + '-' + intExperience.ToString() + '-'
            + decAnnualSalary.ToString();
      }

      public override bool Equals(object obj)
      {
         return this.ToString().Equals(((CEmployee)obj).ToString());
      }

      public override int GetHashCode()
      {
         return this.ToString().GetHashCode();
      }
   }

   class Program
   {
      static void Main(string[] args)
      {
         File.ReadAllLines(@"..\..\Employees.txt")
            .Select(s => s.Trim())
            .Where(s => CEmployee.IsValid(s))
            .Select(s => new CEmployee(s))
            .Select(Employee => new {Key = Employee.intExperience, Value = Employee})
            .ToLookup(k => k.Key, v => v.Value) //groups records by Experience
            .ToList().ForEach(empRpt =>
               Console.WriteLine(
                  "Emp w/ {0} years have combined sal of {1:C2} & avg sal of {2:C2}",
                  empRpt.Key.ToString().PadLeft(2, ' '),
                  empRpt.Select(e => e.decAnnualSalary).Sum(),
                  empRpt.Select(e => e.decAnnualSalary).Average())
            );
      }
   }
}
commented: Great example :) +12

I agree with you thines01. I use classes as much as possible. And lists of course. They all can make your life really easier.

Thank you so much to Mitja and Thines for helping me out. I haven't learned anything about querry and anything advance.
Is there anyway I can solve the rest of the problem with loops after I get the data tryparse from the array?
Once again I'm really appriciate your helps :)

I took this down to dot net 2.0 and removed all LINQ.
This is how I would (still) do it.

I use a Dictionary<int, List<CEmployee>> to help count the number of employesse with the same level of experience.
Feel free to replace the Dictionary with an array of integers and two arrays of decimals.

using System;
using System.Collections.Generic;
using System.IO;

namespace DW_420043_CS_CON
{
   public class CEmployee
   {
      public string strID { get; set; }
      public int intExperience { get; set; }
      public decimal decAnnualSalary { get; set; }

      public CEmployee()
      {
         strID = "";
         intExperience = 0;
         decAnnualSalary = 0;
      }

      public CEmployee(CEmployee copy)
      {
         strID = copy.strID;
         intExperience = copy.intExperience;
         decAnnualSalary = copy.decAnnualSalary;
      }

      public CEmployee(string strCsvData)
      {
         int intDefault = 0;
         decimal decDefault = 0;

         string[] arr_strData = strCsvData.Split(',');
         strID = arr_strData[0];

         int.TryParse(arr_strData[1], out intDefault);
         intExperience = intDefault;

         decimal.TryParse(arr_strData[2], out decDefault);
         decAnnualSalary = decDefault;
      }

      public static bool IsValid(string strData)
      {
         if (2 != (strData.Length - (strData.Replace(",", "").Length)))
         {  // three columns will contain two commas
            return false;
         }

         return strData.StartsWith("EID");
      }

      //////////////////////////////////////////////////////////////////////////
      // some form of these overrides are critical for making distinct objects
      public override string ToString()
      {
         return strID + '-' + intExperience.ToString() + '-'
            + decAnnualSalary.ToString();
      }

      public override bool Equals(object obj)
      {
         return this.ToString().Equals(((CEmployee)obj).ToString());
      }

      public override int GetHashCode()
      {
         return this.ToString().GetHashCode();
      }
   }

   class Program
   {
      private static decimal SumSalary(List<CEmployee> lstEmp)
      {
         decimal decRetVal = 0;
         lstEmp.ForEach(emp => decRetVal += emp.decAnnualSalary);
         return decRetVal;
      }

      static void Main(string[] args)
      {
         string[] arr_strData = File.ReadAllLines(@"..\..\Employees.txt");

         Dictionary<int, List<CEmployee>> map_i2l2oExperience = new Dictionary<int, List<CEmployee>>();

         foreach (string strData in arr_strData)
         {
            if(CEmployee.IsValid(strData))
            {
               CEmployee tempEmp = new CEmployee(strData.Trim());
               if (!map_i2l2oExperience.ContainsKey(tempEmp.intExperience))
               {
                  map_i2l2oExperience.Add(tempEmp.intExperience, new List<CEmployee>());
               }

               map_i2l2oExperience[tempEmp.intExperience].Add(tempEmp);
            }
         }

         foreach (KeyValuePair<int, List<CEmployee>> kvp_i2l2o in map_i2l2oExperience)
         {
            decimal decSumSal = SumSalary(kvp_i2l2o.Value);

            Console.WriteLine(
               "Emp w/ {0} years have combined sal of {1:C2} & avg sal of {2:C2}",
               kvp_i2l2o.Key, decSumSal, (decSumSal / kvp_i2l2o.Value.Count)); 
         }
      }
   }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.