【问题标题】:How to sort Strings in C# [duplicate]如何在C#中对字符串进行排序[重复]
【发布时间】:2016-03-17 17:18:14
【问题描述】:

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

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

有什么简单的方法吗?

【问题讨论】:

  • 到目前为止你有什么代码?
  • 好吧,您可以致电Array.Sort 并传入IComparer<string> 或Comparison<string>...或者您可以使用LINQ...您尝试过什么了吗?发生了什么?
  • 看看这个dotnetperls.com/sort
  • 感谢您的回答,但它需要不使用 LINQ 的解决方案,这就是我创建问题的原因。我应该在之前提到过。
  • @Imugi,所以你应该编写自己的排序方式?

标签: c# string


【解决方案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

【讨论】:

    【解决方案2】:

    您可以通过以下方式使用 LINQ:

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

    另一种方法是将Array.Sort 与自定义IComparer 实现结合使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-21
      • 2013-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多