2012-07-28 233 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的。