如何从数据库(C#)中的数组中删除数据?
问题描述:
我目前正在使用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.
");
}
}
}
答
据我所看到的,您不使用一个真正的数据库,而是在内存中的集合。如果你想保持这样,你应该使用另一个数组结构来存储你的员工。
你应该使用类似一个Dictionary<string, Employee>
其中关键是社会保障号码或HashSet<Employee>
,实施您的Employee类GetHashCode()
和Equals()
。
你有收藏将自动调整大小以及您可以轻松地使用他们的Remove(...)
方法删除项目的方式。
答
我建议你使用通用列表。
private List<Employee> employees = new List<Employee>();
对于您需要:
using System.Collections.Generic;
然后你就可以easliy添加员工是这样的:
employees.Add(emp);
,并清除这样的:
employees.Remove(emp);
你删除方法应该要求某种标识符因此您可以搜索合适的员工并在之后将其删除。
这是一个很大的代码,所以我没有把它都在这里,我所展示的权利,现在正好是类“员工DB”中“创造”的方法。我认为如果我在这里发布全部内容会更有意义。 –