查看您的代码,在我看来,您正在将文本项添加到 ListBox,因此当然要从中获得薪水并不容易。
相反,您应该将 Employee 对象传递给列表框以保留所有必要的信息;这样,您的添加方法将是:
private void btnSave_Click(object sender, EventArgs e)
{
var empid = Convert.ToInt32(txtEmployeeID.Text);
var empfirstname = Convert.ToString(txtEmployeeFirstName.Text);
var emplastname = Convert.ToString(txtEmployeeLastName.Text);
var empsalary = Convert.ToDouble(txtSalary.Text);
var emp = new Employee(empid, empfirstname, emplastname, empsalary);
lstEmployeeData.Items.Add(emp);
}
当然,要得到想要的显示文本,你需要重新定义ToString()
Employee的方法,例如像这样:
class Employee
{
// other methods...
public override string ToString()
{
return this.EmployeeToString();
}
}
最后,当单击“显示最低工资的员工”按钮时,您应该简单地执行以下操作:
private void btnLowestSalary_Click(object sender, EventArgs e)
{
var minSalary = lstEmployeeData.Items.OfType<Employee>().Min(x => x.Salary);
var empWithMinSalary = lstEmployeeData.Items.OfType<Employee>()
.First(x => x.Salary == minSalary);
string msg = string.Format("{0} has the lowest salary of {1}", empWithMinSalary.EmployeeFirstName, minSalary);
MessageBox.Show(msg);
}
编辑 :
如果不止一名员工的薪水相同,您可以执行以下操作:
private void btnLowestSalary_Click(object sender, EventArgs e)
{
var minSalary = lstEmployeeData.Items.OfType<Employee>().Min(x => x.Salary);
var empsWithMinSalary = lstEmployeeData.Items.OfType<Employee>()
.Where(x => x.Salary == minSalary);
foreach(var e in empsWithMinSalary)
{
string msg = string.Format("{0} has the lowest salary of {1}", e.EmployeeFirstName, minSalary);
MessageBox.Show(msg);
}
}
或更好:
private void btnLowestSalary_Click(object sender, EventArgs e)
{
var minSalary = lstEmployeeData.Items.OfType<Employee>().Min(x => x.Salary);
var empsWithMinSalary = lstEmployeeData.Items.OfType<Employee>()
.Where(x => x.Salary == minSalary);
string names = "";
foreach(var e in empsWithMinSalary)
names += Environment.NewLine + e.EmployeeFirstName;
string msg = string.Format("The following emplyoees have the lowest salary of {0} : {1}", minSalary, names);
MessageBox.Show(msg);
}