繁体   English   中英

列表和排序

[英]Lists and Sorting

基本上我在这里要做的是创建我自己的结构并通过获取用户输入,将其添加到列表中,然后以不同的方式(ID等)对其进行排序来利用它。

我认为我正确地构建了结构,但是我无法弄清楚如何比较这两个学生实例,按ID对它们进行排序,并将它们打印出来(按ID排序)到控制台。

有任何想法吗? 我想我正朝着正确的方向前进。

   namespace App26
{
    public struct Student
    {
        public String first, last;
        public double ID;

        public Student(String first, String last, double ID)
        {
            this.first = first;
            this.last = last;
            this.ID = ID;
        }
    }

    class IDCompare : IComparer<Student>
    {
        public int Compare(Student a, Student b)
        {
            return a.first.CompareTo(b.f);
        }
    }


    class Program
    {

        static void Main(string[] args)
        {
            String firstname, lastname, first, last;
            double num, IDnum;

            //First person   
            Console.WriteLine("Please enter first name");
            firstname = Console.ReadLine();
            Console.WriteLine("Please enter last name");
            lastname = Console.ReadLine();
            Console.WriteLine("Please enter ID");
            IDnum = Convert.ToDouble(Console.ReadLine());
            Console.WriteLine();

            //Second Person
            Console.WriteLine("Please enter first name");
            first = Console.ReadLine();
            Console.WriteLine("Please enter last name");
            last = Console.ReadLine();
            Console.WriteLine("Please enter ID");
            num = Convert.ToDouble(Console.ReadLine());
            Console.WriteLine();

            List<Student> list = new List<Student>();
            Student person1 = new Student(firstname, lastname, IDnum);
            //Student person2 = new Student(first, last, num);
            list.Add(person1);
            list.Add(person2);
            list.Sort();

            foreach (Student i in list)
            Console.WriteLine(i);
        }        
       }
}

您应该使用下面的代码进行排序

list.Sort(new IDCompare()); 

return a.first.CompareTo(b.f);

似乎是不正确的。 请检查代码编译时错误。

您的IDCompare不是比较ID,而是首先(我假设名称)。 你应该改变它:

class IDCompare : IComparer<Student>
{
    public int Compare(Student a, Student b)
    {
        return a.ID.CompareTo(b.ID);
    }
}

然后打电话给你这样的排序:

list.Sort(new IDCompare());

请记住,ID通常是整数,而不是双精度(虽然我不知道你的ID是什么意思)。

如果你想使用它

 foreach (Student i in list)
            Console.WriteLine(i);

我建议你覆盖结构中的ToString()方法(为什么不使用类?)

public override string ToString()
{
       return ID.ToString() + " " + first + " " + last + " ";
}

您也可以非常轻松地使用Linq。 那你就不需要实现任何比较器了。

foreach (Student entry in myList.OrderBy(student => student.ID))
  Console.Write(entry.Name);

酒店还提供第二家酒店的排序服务。 您也可以使用降序排序。

foreach (Student entry in myList.OrderBy(student => student.ID).ThenBy(student => student.Name))
  Console.Write(entry.Name);

暂无
暂无

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

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