【问题标题】:How can I sort an object array in C# based on user input?如何根据用户输入在 C# 中对对象数组进行排序?
【发布时间】: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 =&gt; x.CalcSalary()).ToArray()
  • 如果你想使用Array.Sort,那么你想使用this overload,它允许你传递一个IComparer来确定要排序的属性,
  • 请注意,您的 Cleaner 类没有属性 - 这些只是私有字段,具有返回每个值的相关方法。
  • 感谢您的反馈!真的很好地清理了事情,现在更有意义,更干净,更简洁。

标签: c# arrays sorting object


【解决方案1】:

我会将 Legacy code 和 Ňɏssa Pøngjǣrdenlarp 合二为一。

Ňɏssa Pøngjǣrdenlarp 说你的 Cleaner 类没有属性的第一件事。 我删除了你所有的方法并用属性来改变它

    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;
        }
    }

现在我们已经修复了类,我们可以查看Program Main method。 因为我们将清洁器类改为使用属性,所以我们可以轻松地使用 Linq to orderby

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

你会注意到这一行

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

我正在使用 Linq 来订购薪水。 有关 Linq 的更多信息,请查看以下文档 https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/

附注 我想说一致性是关键,这将使您的代码保持干净。 看下面的例子,命名约定不一致

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

漂亮,干净,易于理解

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

【讨论】:

  • 这更有意义,也更容易管理。还消除了整个不必要的代码块。谢谢。
  • 如果您想要的话,标记为已回答
猜你喜欢
  • 2020-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-09
  • 2013-11-25
  • 2016-05-14
  • 2020-12-15
  • 2023-02-03
相关资源
最近更新 更多