2012-11-20 61 views
1

基本上我在这里要做的是创建我自己的结构,并通过接受用户输入,将它添加到列表中,然后以不同方式(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); 
     }   
     } 
} 

回答

1

您的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 + " "; 
} 
+0

感谢你们两位的帮助:)我设法让ID工作,并实施我需要的其他方法。变成var sortedEnumerable = list.OrderBy(p => p.ID);工作得很好:D – user1780149

2

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

list.Sort(new IDCompare()); 

而且

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

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

1

你也可以使用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);