2012-11-20 60 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);