【问题标题】:Sorting a collection in alphabetical order按字母顺序对集合进行排序
【发布时间】:2011-03-30 12:36:47
【问题描述】:

有什么方法可以开箱即用地按字母顺序对集合进行排序(使用 C# 2.0 吗?)。

谢谢

【问题讨论】:

  • @Dominic 那个问题大约是3.5,意思是Linq。
  • @Dominic:我看到 Q 和大多数 A 使用 C#3
  • @Will, @Henk - 抱歉,应该远离我一无所知的话题!
  • @Dom 考虑到 .NET 版本控制的主题对于 c# 开发人员来说已经足够混乱了,可能是这样!

标签: c# sorting


【解决方案1】:

我们在谈论什么样的收藏? List<T>? ICollection<T>?大批?集合中存储的类型是什么?

假设List<string>,您可以这样做:

 List<string> str = new List<string>();
 // add strings to str

 str.Sort(StringComparer.CurrentCulture);

【讨论】:

  • 我不喜欢在一般情况下使用var
  • @thecoop 除非上下文不可见,否则 var 很棒
【解决方案2】:

您可以使用SortedList

【讨论】:

    【解决方案3】:

    Array.Sort 怎么样?即使您不提供自定义比较器,默认情况下它也会按字母顺序对数组进行排序:

    var array = new string[] { "d", "b" };
    
    Array.Sort(array); // b, d
    

    【讨论】:

      【解决方案4】:
      List<string> stringList = new List<string>(theCollection);
      stringList.Sort();
      

      List&lt;string&gt; 实现了ICollection&lt;string&gt;,因此即使转换为列表后,您仍将拥有所有以集合为中心的功能。

      【讨论】:

        【解决方案5】:

        这可能不是开箱即用的,但您也可以使用 LinqBridge http://www.albahari.com/nutshell/linqbridge.aspx 在 2.0 中进行 LINQ 查询(但建议使用 Visual Studio 2008)。

        【讨论】:

          猜你喜欢
          • 2019-04-21
          • 2011-08-29
          • 2010-10-26
          • 2017-05-22
          • 1970-01-01
          • 1970-01-01
          • 2011-01-15
          • 1970-01-01
          相关资源
          最近更新 更多