[英]How to sort a List<string> character by character?
下面的代码;
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();
但是不起作用。
假设您想在数组的末尾而不是列表中使用数组,则应使用正确的顺序排列数组:
string[] mySortedArray = list.OrderBy(x => x.Replace(";", string.Empty)).ToArray()
如果您需要基于原始代码的列表:
list = list.OrderBy(x => x.Replace(";", string.Empty)).ToList()
这里有两点要注意-首先,与您的代码不同,这种类型是递增的,而不是递减的; 其次,要给您结果,您需要在排序时去除分号,否则分号将使结果倾斜,从而导致您希望排在最前面的项目排在最后。
正如评论中指出的那样,您发布的代码中还存在许多其他问题。
您可以实现一个自定义比较器:
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));
排序是就地完成的,无需在任何地方分配结果。
问题是;
来了.
在用于排序的Unicode字符集中 。
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.