简体   繁体   English

如何根据用户输入对 C# 中的 object 数组进行排序?

[英]How can I sort an object array in C# based on user input?

I have an array that is populated with user input and needs to be sorted according to a particular property.我有一个填充了用户输入的数组,需要根据特定属性进行排序。 I have looked at similar questions on here but it does not seem to help my specific situation and so far nothing I've tried has worked.我在这里查看了类似的问题,但它似乎对我的具体情况没有帮助,到目前为止,我尝试过的任何方法都没有奏效。

The properties for the array are defined in a separate class.数组的属性在单独的 class 中定义。

It's a basic program for loading employees onto a system and the output needs to be sorted according to their salary.这是一个将员工加载到系统中的基本程序,output 需要根据他们的工资进行排序。 *Note that I am a student and I am possibly missing something very basic. *请注意,我是一名学生,我可能缺少一些非常基本的东西。

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();

            
        }
    }
}

I will combine Legacy code and Ňɏssa Pøngjǣrdenlarp into one.我会将 Legacy code 和 Ňɏssa Pøngjǣrdenlarp 合二为一。

First thing as Ňɏssa Pøngjǣrdenlarp said your Cleaner class has no properties.首先,Ňɏssa Pøngjǣrdenlarp 说您的清洁器 class 没有属性。 I removed all your methods and changed it with properties instead我删除了你所有的方法并用属性改变了它

    public class Cleaner
    {
        public Cleaner(long staffId, string name, string surname, int number, int hours)
        {
            StaffNo = staffId;
            FName = name;
            LastName = surname;
            Contact = number;
            NoHours = hours;
        }
    
        public long StaffNo { get; set; }
    
        public string LastName { get; set; }
    
        public string FName { get; set; }
    
        public int Contact { get; set; }
    
        public int NoHours { get; set; }
    
        public double Rate => 380.00;
    
        public double Salary
        {
            get
            {
                double salary = 0;
    
                if (NoHours > 0 && NoHours <= 50)
                {
                    salary = NoHours * Rate;
                }
                else if (NoHours > 50)
                {
                    salary = (NoHours * Rate) + 5000;
                }
    
                return salary;
            }
        }
    
        public override string ToString()
        {
            return "\n Staff no: " + StaffNo + "\n Surname" + LastName
                + "\n Name: " + FName + "\n Contact no: " + Contact;
        }
    }

Now that we have fixed the class we can look at the Program Main method .现在我们已经修复了 class 我们可以查看Program Main method Because we changed the cleaner class to use properties instead we can easily use Linq to orderby因为我们将清洁器 class 改为使用属性,所以我们可以轻松地使用 Linq 来订购

private static void Main(string[] args)
{
    //Cleaner cleaner = new Cleaner(); // Instantiantion

    // Object Array
    var clean = new Cleaner[3]; // Empty Object Array
    var loadedCleaners = LoadCleaners(clean).OrderBy(_ => _.Salary).ToArray();

    foreach (Cleaner v in loadedCleaners)
    {
        Console.WriteLine(" ");
        Console.WriteLine(v + "\n Salary: R" + v.Salary);
    }

    Console.ReadKey();
}

You will notice that on this line你会注意到在这条线上

var loadedCleaners = LoadCleaners(clean).OrderBy(_ => _.Salary).ToArray();

that i am using Linq to order the Salary.我正在使用 Linq 来订购薪水。 For more on Linq check out the following docs https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/有关 Linq 的更多信息,请查看以下文档https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/

On a side note I would say consistency is key, this will keep your code clean.在旁注中,我会说一致性是关键,这将使您的代码保持干净。 Look at the following example, the naming convention is inconsistent看下面的例子,命名约定不一致

public Cleaner(long staffId, string name, string surname, int number, int hours)
{
    StaffNo = staffId;
    FName = name;
    LastName = surname;
    Contact = number;
    NoHours = hours;
}

Nice, clean and easy to follow漂亮,干净,易于遵循

public Cleaner(long staffId, string firstName, string lastName, int number, int hours)
{
    StaffId = staffId;
    FirstName = firstName;
    LastName = lastName;
    Number = number;
    Hours = hours;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM