2016-03-17 43 views
-3

我必须对字符串数组进行排序。我该怎么做,如果:如何在C中对字符串进行排序#

  1. 它们必须按字符串长度的顺序放置。
  2. 如果长度相等,则必须按字母顺序排列。

有什么简单的办法吗?

+1

什么样的代码你有这么远吗? – Amy

+3

那么你可以调用'Array.Sort'并传递一个'IComparer '或一个'Comparison '......或者你可以使用LINQ ......你有没有尝试过任何东西?发生了什么? –

+0

看看这个http://www.dotnetperls.com/sort – user990423

回答

1

下面是在C#中的传统方式...

static void Main(string[] args) 
{ 
    List<string> list = new List<string>(); 
    list.Add("1991728819928891"); 
    list.Add("0991728819928891"); 
    list.Add("3991728819928891"); 
    list.Add("2991728819928891"); 
    list.Add("Hello"); 
    list.Add("World"); 
    list.Add("StackOverflow"); 
    list.Sort(
     delegate (string a, string b) { 
      int result = a.Length.CompareTo(b.Length); 
      if (result == 0) 
       result = a.CompareTo(b); 
      return result; 
     } 
    ); 

    Console.WriteLine(string.Join("\n", list.ToArray())); 
} 

样本输出:

Hello 
World 
StackOverflow 
0991728819928891 
1991728819928891 
2991728819928891 
3991728819928891 
1

您可以通过以下方式与LINQ做到这一点:

string[] arr = new[] { "aa", "b", "a" , "c", "ac" }; 
var res = arr.OrderBy(x => x.Length).ThenBy(x => x).ToArray(); 

另一种方法是使用Array.Sort定制IComparer实现。

相关问题