【发布时间】:2020-10-22 03:05:52
【问题描述】:
我有一个由用户输入填充的数组,需要根据特定属性进行排序。我在这里查看了类似的问题,但它似乎对我的具体情况没有帮助,到目前为止我尝试过的任何方法都没有奏效。
数组的属性在单独的类中定义。
这是一个将员工加载到系统中的基本程序,输出需要根据他们的薪水进行排序。 *请注意,我是一名学生,我可能缺少一些非常基本的东西。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.AccessControl;
using System.Text;
using System.Threading.Tasks;
namespace Instantiating_Objects
{
class Program
{
static void Main(string[] args)
{
//Cleaner cleaner = new Cleaner(); // Instantiantion
// Object Array
Cleaner[] clean = new Cleaner[3]; // Empty Object Array
Cleaner[] loadedCleaners = LoadCleaners(clean);
for (int i = 0; i < loadedCleaners.Length; i++)
{
Console.WriteLine(" ");
Console.WriteLine(loadedCleaners[i].Display() + "\n Salary: R" + loadedCleaners[i].CalcSalary());
}
Console.ReadKey();
}
public static Cleaner[] LoadCleaners(Cleaner[] cleaner)
{
for (int i = 0; i < cleaner.Length; i++)
{
Console.WriteLine("Enter your staff number");
long id = Convert.ToInt64(Console.ReadLine());
Console.WriteLine("Enter your last name");
string lname = Console.ReadLine();
Console.WriteLine("Enter your first name");
string fname = Console.ReadLine();
Console.WriteLine("Enter your contact number");
int contact = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter your number of hours worked");
int hours = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("");
// Populating object array
cleaner[i] = new Cleaner(id, fname, lname, contact, hours);
}
Array.Sort(, )
return cleaner;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Instantiating_Objects
{
class Cleaner
{
private long staffNo;
private string lastName;
private string fName;
private int contact;
private int noHours;
private double rate = 380.00;
public Cleaner() { }
public Cleaner(long staffId, string name, string surname, int number, int hours)
{
this.contact = number;
this.fName = surname;
this.lastName = name;
this.staffNo = staffId;
this.noHours = hours;
}
public int GetHours() { return noHours;}
public long GetStaffID() { return staffNo; }
public string GetSurname() { return lastName; }
public string GetName() { return fName; }
public int GetNumber() { return contact; }
// Calculate Salary
public double CalcSalary()
{
double salary = 0;
if(GetHours() > 0 && GetHours() <= 50)
{
salary = GetHours() * rate;
}
else if (GetHours() > 50)
{
salary = (GetHours() * rate) + 5000;
}
return salary;
}
public string Display()
{
return "\n Staff no: " + GetStaffID() + "\n Surname" + GetSurname()
+ "\n Name: " + GetName() + "\n Contact no: " + GetNumber();
}
}
}
【问题讨论】:
-
使用 Linq...Linq 永远是答案 :)
return cleaner.OrderBy(x => x.CalcSalary()).ToArray() -
如果你想使用
Array.Sort,那么你想使用this overload,它允许你传递一个IComparer来确定要排序的属性, -
请注意,您的 Cleaner 类没有属性 - 这些只是私有字段,具有返回每个值的相关方法。
-
感谢您的反馈!真的很好地清理了事情,现在更有意义,更干净,更简洁。