简体   繁体   中英

How to delete a data from an array in a database (C#)?

I am currently working on a Employee Database using C#. I have 4 different classes which makes up my database; Salaried Employee, Hourly Employee, Commission Employee, and Base-Salaried Employee. I have a base class called "employee" which holds the first name, last name and SSN of each employee type.

At the moment, I am able to individually print each employee when I run the code. I use a test input file which test what type of employee is in the file. It outputs it in an output file with its corresponding type of employee.

Now that, I am able to create an employee record, I also want to be able to remove an employee record from the array.

The method I have for this is called

 private void DeleteEmployeeRecord()
        {
            Console.WriteLine("***** DeleteEmployeeRecord");
        }

I am having trouble with getting started with this method. Any tips or idea on how I could delete an employee from the array?

Below is the code for the Employee Database in which does all the operations for the system such as creating a record for employee, finding a record of employee, deleting a record of employee, etc. As I've mentioned, I only have the Create method working and not the rest. I would gladly appreciate any help I can get with understanding how to delete an employee from my temporary array.

**EmployeeDB:**
    using System;
using System.IO;

namespace PayrollDB
{
    internal class EmployeeDB
    {
        public const string SALARIED = "SALARIED";
        public const string BASEPLUS = "BASEPLUS";
        public const string COMMISSION = "COMMISSION";
        public const string HOURLY = "HOURLY";

        public const char CREATE_C = 'C';
        public const char CREATE_c = 'c';
        public const char SALARIED_S = 'S';
        public const char SALARIED_s = 's';
        public const char BASEPLUS_B = 'B';
        public const char BASEPLUS_b = 'b';
        public const char COMMISSION_M = 'M';
        public const char COMMISSION_m = 'm';
        public const char HOURLY_H = 'H';
        public const char HOURLY_h = 'h';

        // storage for all the students during the database operations
        private Employee[] employees;

        public EmployeeDB()
        {
        }

        internal void ReadDataFromInputFile()
        {
            // create and intialize the file objects
            FileStream fstream = new FileStream("INPUT.txt", FileMode.Open, FileAccess.Read);
            StreamReader infile = new StreamReader(fstream);   // FileStream

            int numberOfRecords = int.Parse(infile.ReadLine());
            employees = new Employee[numberOfRecords];

            for (int i = 0; i < employees.Length; i++)
            {
                string employeeType = infile.ReadLine();

                // read in data for an employee
                string firstName = infile.ReadLine();
                string lastName = infile.ReadLine();
                string socialSecurityNumber = infile.ReadLine();

                // how many more things are there to read?
                if(employeeType == SALARIED)
                {
                    decimal weeklySalary = decimal.Parse(infile.ReadLine());

                    // make a employee using the data you just read
                    // put the employee into the array
                    employees[i] = new Salaried(firstName, lastName, socialSecurityNumber, weeklySalary);

                }
                else if(employeeType == BASEPLUS)
                {
                    decimal grossSales = decimal.Parse(infile.ReadLine());
                    decimal commissionRate = decimal.Parse(infile.ReadLine());
                    decimal baseSalary = decimal.Parse(infile.ReadLine());
                    // make an employee using the data you just read
                    // put the employee into the array
                    employees[i] = new BasePlus(firstName, lastName, socialSecurityNumber, grossSales, commissionRate, baseSalary);
                }
                else if (employeeType == COMMISSION)
                {
                    decimal grossSales = decimal.Parse(infile.ReadLine());
                    decimal commissionRate = decimal.Parse(infile.ReadLine());

                    // make a student using the data you just read
                    // put the student into the array
                    employees[i] = new Commission(firstName, lastName, socialSecurityNumber, grossSales, commissionRate);
                }
                else if (employeeType == HOURLY)
                {
                    decimal hourlyWage = decimal.Parse(infile.ReadLine());
                    decimal hoursWorked = decimal.Parse(infile.ReadLine());

                    // make a student using the data you just read
                    // put the student into the array
                    employees[i] = new Hourly(firstName, lastName, socialSecurityNumber, hourlyWage, hoursWorked);
                }
                else
                {
                    Console.WriteLine("ERROR: That is not a valid employee type.");
                }
            }

            // close the file or release the resource
            infile.Close();
        }
        internal void WriteDataToOutputFile()
        {
            // create and open an output file
            FileStream fstream = new FileStream("OUTPUT.txt", FileMode.Create, FileAccess.Write);
            StreamWriter outfile = new StreamWriter(fstream);

            // write the size of the array
            outfile.WriteLine(employees.Length);

            // write the data from the objects in the array to the output file
            foreach (var employee in employees)
            {
                if (employee is Hourly)
                {
                    var hourly = (Hourly)employee;
                    outfile.Write(hourly.ToDataFileString());
                }
                else if (employee is Salaried)
                {
                    var salaried = (Salaried)employee;
                    outfile.Write(salaried.ToDataFileString());
                }
                else if (employee is Commission)
                {
                    var commission = (Commission)employee;
                    outfile.Write(commission.ToDataFileString());
                }
                else if (employee is BasePlus)
                {
                    var baseplus = (BasePlus)employee;
                    outfile.Write(baseplus.ToDataFileString());
                }
            }

            // close the output file
            outfile.Close();
        }


        public void PrintAllRecords()
        {
            Console.WriteLine("** Contents of db ***************");
            foreach (var emp in employees)
            {
                Console.WriteLine(emp);
            }
        }


        // main method that operates the application once we get
        // all the data read into it
        internal void OperateDatabase()
        {
            // explain the program to the user 
            DisplayProgramExplanation();

            ConsoleKeyInfo choice;
            do
            {
                // user interface
                PresentUserInterface();
                //string choice = Console.ReadLine();
                //selection = choice[0];

                choice = Console.ReadKey();

                switch(choice.KeyChar)
                {
                    case CREATE_C:
                    case CREATE_c:
                        CreateEmployeeRecord();
                        break;
                    case 'F':
                    case 'f':
                        FindAndPrintEmployeeRecord();
                        break;
                    case 'U':
                    case 'u':
                        UpdateEmployeeRecord();
                        break;
                    case 'D':
                    case 'd':
                        DeleteEmployeeRecord();
                        break;
                    case 'P':
                    case 'p':
                        PrintAllEmployeeRecords();
                        break;
                    default:
                        break;
                }

            } while ((choice.KeyChar != 'Q') && (choice.KeyChar != 'q'));

        }

        private void FindAndPrintEmployeeRecord()
        {
            throw new NotImplementedException();
        }

        private void PrintAllEmployeeRecords()
        {
            Console.WriteLine("***** PrintAllEmployeeRecords");
        }

        private void DeleteEmployeeRecord()
        {
            Console.WriteLine("***** DeleteEmployeeRecord");
        }

        private void UpdateEmployeeRecord()
        {
            Console.WriteLine("***** UpdateEmployeeRecord");
        }

        // Find a student object in the array.
        // Inputs: email - a string containing the email address of 
        // the student that is being searched for
        // Output: the student object with a matching email, otherwise null ref
        private Employee FindEmployeeRecord(string socialSecurityNumber)
        {
            // look through the collection at each employee
            foreach (var emp in employees)
            {
                // if we find a student with matching social security number
                if(emp.SocialSecurityNumber == socialSecurityNumber)
                {
                    // return the object
                    return emp;
                }
            }

            // if we get through the entire collection with no student
            // object find that matches the search email, 
            // so return a null reference
            return null;
        }

        private void CreateEmployeeRecord()
        {
            Console.WriteLine(" :: CreateStudentRecord");

            //display prompt that asks for employee's social security number
            Console.Write("Enter the social security number for the record to add: ");

            //user types in the student email
            string socialSecurityNumber = Console.ReadLine();

            // check to see if record already exists in the database
            // if it does, return back to main menu, issue a message
            Employee emp = FindEmployeeRecord(socialSecurityNumber);
            if(emp != null)
            {
                Console.WriteLine("Error: " + socialSecurityNumber + " is already in the database.");
                return;
            }

            //display prompt that asks for type of student
            Console.Write("Enter the type of employee: ");
            ConsoleKeyInfo employeeType = Console.ReadKey();

            //display prompt that asks for first name
            Console.Write("Enter the first name: ");
            string firstName = Console.ReadLine();

            //display prompt that asks for last name
            Console.Write("Enter the last name: ");
            string lastName = Console.ReadLine();

            // if type of student was U
            if(employeeType.KeyChar == SALARIED_S || employeeType.KeyChar == SALARIED_s)
            {
                //display prompts for the weekly salary
                Console.Write("Enter the weekly salary: ");
                decimal weeklySalary = decimal.Parse(Console.ReadLine());

                // make an undergrad student
                emp = new Salaried(firstName, lastName, socialSecurityNumber, weeklySalary);
            }
            else if (employeeType.KeyChar == BASEPLUS_B || employeeType.KeyChar == BASEPLUS_b)
            {
                //if student type is BasePlus Employee prompt for base salary
                Console.Write("Enter the Base Salary: ");
                decimal baseSalary = decimal.Parse(Console.ReadLine());

                // prompt for the Gross Sales
                Console.Write("Enter the Gross Sales: ");
                decimal grossSales = decimal.Parse(Console.ReadLine());

                //prompt for the Commission Rate
                Console.Write("Enter the Commission Rate: ");
                decimal commissionRate = decimal.Parse(Console.ReadLine());

                // make a grad student
                emp = new BasePlus(firstName, lastName, socialSecurityNumber, grossSales, commissionRate, baseSalary);
            }
            else if (employeeType.KeyChar == COMMISSION_M || employeeType.KeyChar == COMMISSION_m)
            {
                // prompt for the Gross Sales
                Console.Write("Enter the Gross Sales: ");
                decimal grossSales = decimal.Parse(Console.ReadLine());

                //prompt for the Commission Rate
                Console.Write("Enter the Commission Rate: ");
                decimal commissionRate = decimal.Parse(Console.ReadLine());

                // make a grad student
                emp = new Commission(firstName, lastName, socialSecurityNumber, grossSales, commissionRate);
            }
            else if (employeeType.KeyChar == HOURLY_H || employeeType.KeyChar == HOURLY_h)
            {
                //if student type is BasePlus Employee prompt for base salary
                Console.Write("Enter the Hourly Wage: ");
                decimal hourlyWage = decimal.Parse(Console.ReadLine());

                // prompt for the Gross Sales
                Console.Write("Enter the Hours Worked: ");
                decimal hoursWorked = decimal.Parse(Console.ReadLine());

                // make a grad student
                emp = new Hourly(firstName, lastName, socialSecurityNumber, hourlyWage, hoursWorked);
            }
            else
            {
                Console.WriteLine(employeeType.KeyChar + " is not a type of employee.");
                return;
            }

            //display the current student data and ask for confirm
            // ask user to confirm

            // the db saves the record, and returns to main menu - steps:
            // and insert the newly created student object into the array

            // 1 - make an array that is 1 "bigger" than students
            Employee[] biggerEmployeeArray = new Employee[employees.Length + 1];

            // 2 - copy all objects from students to the bigger array
            // (at the same index val)
            for (int i = 0; i < employees.Length; i++)
            {
                biggerEmployeeArray[i] = employees[i];
            }

            // put stu in the last slot in the bigger array
            biggerEmployeeArray[biggerEmployeeArray.Length - 1] = emp;

            // make the students ref point to the bigger array
            employees = biggerEmployeeArray;
        }

        private void PresentUserInterface()
        {
            Console.WriteLine(@"
Select from the following options:
[C]reate (a new employee)
[F]ind (search for a record)
[U]pdate
[D]elete
[P]rint all records in the database
[Q]uit
");
        }

        private void DisplayProgramExplanation()
        {
            Console.WriteLine(@"
********************************************
Welcome to the Employee Database application.
You can execute most typical db commnds,
including
[C]reate, [R]ead [U]pdate, and [D]elete
for the employee records that are present.
");
        }
    }
}

AS far as I can see, you are not using a real database, but rather an In-Memory-Collection. If you want to keep it like that, you should use another data-structure than an array to store your employees.

You should use something like a Dictionary<string, Employee> where the Key is the social security number, or a HashSet<Employee> and implement GetHashCode() and Equals() in your Employee class.

That way you have collections that will auto-size and from which you can easily remove items using their Remove(...) method.

I suggest you to use a generic List.

private List<Employee> employees = new List<Employee>();

For that you need:

using System.Collections.Generic;

Then you can easliy add employee like this:

employees.Add(emp);

And remove the like this:

employees.Remove(emp);

Your delete method should ask for some kind if identifier so you can search for the right employee and remove him/her afterwards.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM