我有一个由15名雇员组成的数组,我想在列表框中显示薪水最低的雇员。但是,当我有多于一个低薪员工时,它只打印其中15张。您能告诉我如何打印所有薪水最低的员工吗?代码位于lowerSalaryCheck()方法中。
namespace ProgrammingAssignment
{
public partial class Form1 : Form
{
Employee[] myEmployee = new Employee[15];
public string theFirst;
public string theLast;
public int theID;
public double theSalary;
public bool continueLoop;
public Form1()
{
InitializeComponent();
}
private void addEmployees()
{
do
{
try
{
theFirst = Convert.ToString(firstBox.Text);
theLast = Convert.ToString(lastBox.Text);
theID = Convert.ToInt32(idBox.Text);
theSalary = Convert.ToDouble(salaryBox.Text);
if (theFirst.Length > 0 && theLast.Length > 0 && theID > 0 && theSalary > 0)
{
for (int i = 0; i < myEmployee.Length; i++)
{
Employee emp = new Employee(theFirst, theLast, theID, theSalary);
myEmployee[i] = emp;
}
}
continueLoop = false;
}
catch (DivideByZeroException dz)
{
Console.WriteLine(dz.Message);
Console.WriteLine("Zero is an invalid number.");
}
catch (FormatException fe)
{
Console.WriteLine(fe.Message);
Console.WriteLine("Please add a valid number.");
}
} while (continueLoop);
}
private void lowestSalaryCheck()
{
var theSal = myEmployee.Min(em => em.yearlySalary);
var theMin = myEmployee.Where(em => em.yearlySalary == theSal);
foreach (var emp in theMin)
{
string message = string.Format("Lowest Salary: {0} {1} {2} {3}", emp.firstName, emp.lastName, emp.id, theSal);
lowestList.Items.Add(message);
}
}
private void saveBtn_Click(object sender, EventArgs e)
{
addEmployees();
}
private void lowestSalary_Click(object sender, EventArgs e)
{
lowestSalaryCheck();
}
}
}
当您添加新的时Employee
,您似乎将Employee
列表中的所有现有替换为新添加的:
for (int i = 0; i < myEmployee.Length; i++)
{
Employee emp = new Employee(theFirst, theLast, theID, theSalary);
myEmployee[i] = emp;
}
每次调用addEmployees
函数时,此循环都会运行15次,并将myEmployee
数组的每个元素替换为新创建的Employee
。
我认为,应该使用动态集合,而不是Employee[] myEmployee = new Employee[15];
可以使用List<Employee> myEmployee = new ArrayList<Employee>();
然后代替
for (int i = 0; i < myEmployee.Length; i++)
{
Employee emp = new Employee(theFirst, theLast, theID, theSalary);
myEmployee[i] = emp;
}
你可以用
Employee emp = new Employee(theFirst, theLast, theID, theSalary);
myEmployee.Add(emp);
之后,您的代码应该可以工作了,因为我看不到您的LINQ查询有问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句