2017-02-23 11 views
0

В настоящее время я работаю над базой данных сотрудников, используя C#. У меня есть 4 разных класса, которые составляют мою базу данных; Наемный работник, почасовый сотрудник, сотрудник комиссии и работник, работающий на основе базы. У меня есть базовый класс под названием «employee», который содержит имя, фамилию и SSN каждого типа сотрудников.Как удалить данные из массива в базе данных (C#)?

На данный момент я могу индивидуально печатать каждого сотрудника при запуске кода. Я использую тестовый входной файл, который проверяет, какой тип сотрудника находится в файле. Он выводит его в выходной файл с соответствующим типом сотрудника.

Теперь, когда я могу создать запись сотрудника, я также хочу удалить запись сотрудника из массива.

метод у меня есть для этого называется

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

У меня возникли проблемы с началом работы с этим методом. Любые советы или идеи о том, как я могу удалить сотрудника из массива?

Ниже приведен код базы данных сотрудников, в котором выполняются все операции для системы, такие как создание записи для сотрудника, поиск записи сотрудника, удаление записи сотрудника и т. Д. Как я уже упоминал, я только работает метод Create, а не остальные. Я с удовольствием позабочусь о любой помощи, которую я смогу понять, как удалить сотрудника из моего временного массива.

**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. 
"); 
     } 
    } 
} 

ответ

0

Насколько я могу судить, вы не используете настоящую базу данных, а скорее коллекцию в памяти. Если вы хотите сохранить его таким образом, вы должны использовать другую структуру данных, чем массив для хранения ваших сотрудников.

Вы должны использовать что-то вроде Dictionary<string, Employee> где ключ номер социального обеспечения или HashSet<Employee> и осуществлять GetHashCode() и Equals() в классе Employee.

Таким образом, у вас есть коллекции, которые будут автоматически устанавливаться и с которых вы можете легко удалить элементы, используя их метод Remove(...).

+0

это много кода, поэтому я не использовал все это здесь, то, что я показываю прямо сейчас, это всего лишь метод «создать» в классе «Employee DB». Я думаю, что было бы более разумно, если бы я опубликовал все это здесь. –

0

Предлагаю вам использовать общий список.

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

Для этого вам необходимо:

using System.Collections.Generic; 

Затем позволяют с легкостью добавить работника, как это:

employees.Add(emp); 

И удалить так:

employees.Remove(emp); 

Ваше удаление метод должен запрашивать какой-то тип, если идентификатор так что вы можете искать подходящего сотрудника и впоследствии удалить его/ее.

Смежные вопросы