[英]How to sort a List<string> character by character?
Below code; 下面的代码;
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());
}
How can I always get the sorting result below? 我怎么总是能得到下面的排序结果?
using System;
using System.Collections.Generic;
using System.Linq;
I had tried 我试过了
List = List.OrderByDescending(x => x).ToList();
But doesn't work. 但是不起作用。
Assuming you want an array at the end, rather than a list, using this should give you a correctly ordered array: 假设您想在数组的末尾而不是列表中使用数组,则应使用正确的顺序排列数组:
string[] mySortedArray = list.OrderBy(x => x.Replace(";", string.Empty)).ToArray()
If you require a list, based on your original code: 如果您需要基于原始代码的列表:
list = list.OrderBy(x => x.Replace(";", string.Empty)).ToList()
There are two things to note here - firstly, unlike your code, this sort is ascending, not descending; 这里有两点要注意-首先,与您的代码不同,这种类型是递增的,而不是递减的; secondly, to give you the result you require you need to strip out the semi-colons while sorting, otherwise they will skew the results, causing the item you wish to be first to come last.
其次,要给您结果,您需要在排序时去除分号,否则分号将使结果倾斜,从而导致您希望排在最前面的项目排在最后。
As pointed out in the comments though, there are a number of other issues present in the code you posted. 正如评论中指出的那样,您发布的代码中还存在许多其他问题。
You could implement a custom comparer: 您可以实现一个自定义比较器:
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, ";", "");
}
}
This will provide sorting based on 'stripped' values, like: 这将提供基于“剥离”值的排序,例如:
"using System.Collections.Generic"
“使用System.Collections.Generic”
and call Sort() method: 并调用Sort()方法:
list.Sort(new AssemblyNameComparer(StringComparer.CurrentCulture));
Sort is done in-place, there's no need to assign result anywhere. 排序是就地完成的,无需在任何地方分配结果。
The problem is that ;
问题是
;
comes after .
来了
.
in the Unicode character set which is used for sorting. 在用于排序的Unicode字符集中 。
list.OrderBy(x => x)
using System.Collections.Generic;
using System.Linq;
using System; <=== ; comes after dot
If you convert all ;
如果全部转换
;
characters to !
字符到
!
(which comes before .
in Unicode) then strings containing semicolons will move upwards. (在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.