2012-07-28 197 views
0

我是非常新的編程,並且正在學習C#。第4周!字符串按字母順序排列的對象(名稱)

寫程序要求用戶輸入:

  • 友名
  • 電話
  • 月出生
  • 出生的年份。

創建作爲對象的數組,並使用了IComparable啓用對象比較。 需要按字符串按字母順序對對象進行排序,並且我認爲除了獲取要比較的字符串外,我還有其他所有代碼。下面是我對IComparable.CompareTo(Object o)

int IComparable.CompareTo(Object o) 
{ 
    int returnVal; 

    Friend temp = (Friend)o; 
    if(this.Name > temp.Name) 
     returnVal = 1; 
    else 
     if(this.Name < temp.Name) 
      returnVal = -1; 
     else returnVal = 0; 
    return returnVal; 
} 

編譯時我收到的錯誤是:

CS0019操作員「>」不能應用於類型「串」和「串」的操作數。

指導員沒有太大的幫助,文字沒有綜合這個意外情況。

回答

3

只是委託給String.CompareTo

int IComparable.CompareTo(Object o) { 
    Friend temp = (Friend)o; 

    return this.Name.CompareTo(temp.Name); 
} 
+0

您應該意識到這會執行「[使用當前文化的區分大小寫和文化敏感的比較](http://msdn.microsoft.com/zh-cn/library/35f0x18w.aspx)」,它可能會或者可能不是必需的。 – svick 2012-07-29 00:24:51

0

這將使用你可能不使用一對夫婦的語言功能,但確實讓喜歡輕鬆一點:

people = people.OrderBy(person => person.Name).ToList(); 

使用,如:

var rnd = new Random(); 
var people = new List<Person>(); 
for (int i = 0; i < 10; i++) 
    people.Add(new Person { Name = rnd.Next().ToString() }); 

//remember, this provides an alphabetical, not numerical ordering, 
//because name is a string, not numerical in this example. 
people = people.OrderBy(person => person.Name).ToList(); 

people.ForEach(person => Console.WriteLine(person.Name)); 
Console.ReadLine(); 

Google LINQ [並記住添加'using System.Linq;']和Lambda的。