2017-02-23 15 views
0

저는 현재 C#을 사용하여 직원 데이터베이스에서 작업하고 있습니다. 나는 나의 데이터베이스를 구성하는 4 가지 클래스를 가지고있다; 샐러리맨, 시간 종업원, 커미션 종업원 및 기본 봉급 사원. 나는 각 종업원 유형의 이름, 성 및 SSN을 보유하는 "employee"라는 기본 클래스를 가지고 있습니다.데이터베이스 (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> 같은 것을 사용하고 Employee 클래스에 GetHashCode()Equals()를 구현해야합니다.

그런 식으로 자동 크기가 적용되며 컬렉션에서 Remove(...) 방법을 사용하여 항목을 쉽게 삭제할 수 있습니다.

+0

코드가 너무 많아서 여기에 모든 것을 넣지 않았습니다. 지금 보여주고있는 것은 "Employee DB"클래스 내에서 "만드는 방법"입니다. 나는 모든 것을 여기에 올리면 더 의미가 있다고 생각합니다. –

0

일반 목록을 사용하는 것이 좋습니다. 이를 위해

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

이 필요합니다

employees.Add(emp); 

을 그리고 같은 제거 :

using System.Collections.Generic; 

그럼 당신은 easliy과 같이 직원을 추가 할 수 있습니다

employees.Remove(emp); 

귀하의 삭제를 메서드는 식별자가 무엇인지 물어보아야합니다. 따라서 올바른 직원을 검색하고 나중에 해당 직원을 제거 할 수 있습니다.