我有我的String类设置,并创建了一个StringComparer
实现IComparer
并希望对我的字符串数组进行排序Rank
并显示它的类.目前它显示:
一个,X,C
当我有点上Rank
.为什么会这样?它应该显示:
A,C,X
或者一夜之间改变了字母?
class Program { static void Main(string[] args) { String[] strings = { new String() { Name = "1123", Rank = "a" }, new String() { Name = "3123", Rank = "x" }, new String() { Name = "3134311", Rank = "c" } }; StringComparer comparer = new StringComparer(); comparer.SortBy = StringComparer.CompareField.Name; Array.Sort(strings, comparer); foreach (String s in strings) { Console.WriteLine(s.Name); } comparer.SortBy = StringComparer.CompareField.Rank; Array.Sort(strings, comparer); foreach (String s in strings) { Console.WriteLine(s.Rank); } } } class String { public string Name { get; set; } public string Rank { get; set; } } class StringComparer : IComparer{ public enum CompareField { Name, Rank } public CompareField SortBy = CompareField.Name; public int Compare(String x, String y) { switch (SortBy) { case CompareField.Name: return x.Name.CompareTo(y.Name); case CompareField.Rank: return x.Name.CompareTo(y.Rank); } return x.Name.CompareTo(y.Name); } }
Richard Iron.. 7
你在做
x.Name.CompareTo(y.Rank)
(比较姓名和职级)
代替
x.Rank.CompareTo(y.Rank)
(比较排名和排名)
你在做
x.Name.CompareTo(y.Rank)
(比较姓名和职级)
代替
x.Rank.CompareTo(y.Rank)
(比较排名和排名)