[英]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.