如何按字符对List <string>字符进行排序?

时间:2017-11-23 09:07:17

标签: c# list sorting

下面的代码;

static void Main(string[] args)
{
    List<string> list = new List<string>();
    list.Add("using System;");
    list.Add("using System.Linq;");
    list.Add("using System.Collections.Generic;");
    Console.WriteLine(RandomPassword());
}

如何始终获得下面的排序结果?

using System;  
using System.Collections.Generic;  
using System.Linq;  

我曾尝试过

List = List.OrderByDescending(x => x).ToList();

但是不起作用。

3 个答案:

答案 0 :(得分:3)

假设你想要一个数组,而不是一个列表,使用它应该给你一个正确排序的数组:

string[] mySortedArray = list.OrderBy(x => x.Replace(";", string.Empty)).ToArray()

如果您需要基于原始代码的列表:

list = list.OrderBy(x => x.Replace(";", string.Empty)).ToList()

这里有两点需要注意 - 首先,与你的代码不同,这种类型是升序而不是降序;第二,为了给你你需要的结果,你需要在分拣时去除分号,否则它们会使结果偏斜,导致你希望首先出现的项目。

正如评论中指出的那样,您发布的代码中还存在许多其他问题。

答案 1 :(得分:0)

您可以实现自定义比较器:

class AssemblyNameComparer : IComparer<string>
    {
        private readonly IComparer<string> _baseComparer;
        public AssemblyNameComparer(IComparer<string> baseComparer)
        {
            _baseComparer = baseComparer;
        }

        public int Compare(string x, string y)
        {
            string xTrimmed = RemoveSemicolon(x);
            string yTrimmed = RemoveSemicolon(y);
            return _baseComparer.Compare(xTrimmed, yTrimmed);
        }

        string RemoveSemicolon(string x)
        {
            return Regex.Replace(x, ";", "");
        }
    }

这将提供基于“剥离”值的排序,例如:

  

“使用System.Collections.Generic”

并调用Sort()方法:

        list.Sort(new AssemblyNameComparer(StringComparer.CurrentCulture));

排序是就地完成的,不需要在任何地方分配结果。

答案 2 :(得分:0)

问题是;位于用于排序的Unicode character set .之后。

list.OrderBy(x => x)

    using System.Collections.Generic;
    using System.Linq;
    using System;                      <=== ; comes after dot

如果您将所有;个字符转换为!(在Unicode中.之前),则包含分号的字符串将向上移动。

list.OrderBy(x => x.Replace(";", "!"))

    using System;                      <=== ! comes before dot
    using System.Collections.Generic;
    using System.Linq;
相关问题