[英]Natural Sort Alpha-numeric like Windows Explorer in C#
我正在尋找像 Windows explorer 這樣的自然排序技術。
例如,如果我有字母數字數組 -
var array = new[]{"B01 002", "B01 0010", "01", "B01 001", "B10 001", "B01 01", "1", "B1 001", "B02 001", "A1"};
我希望這將按以下順序排序-
[01, 1, A1, B01 001, B01 01, B01 002, B01 0010, B1 001, B02 001, B10 001]
這正是 Windows Explorer 的做法——
我已經嘗試了以下線程中的解決方案-
對所采取的方法沒有其他限制。 可以使用 LINQ、Regex、Extention 或接口方法來復制“shlwapi.dll”完成的排序順序
我建議將字符串拆分為塊,其中每個塊都是數字或沒有數字: "B01 001" -> {"B", "01", " ", "001"}
。 然后比較這些塊(比較兩個全數字塊是一種特殊情況)。
代碼:(小提琴)
public sealed class NaturalComparer : IComparer<string> {
private static int CompareChunks(string x, string y) {
if (x[0] >= '0' && x[0] <= '9' && y[0] >= '0' && y[0] <= '9') {
string tx = x.TrimStart('0');
string ty = y.TrimStart('0');
int result = tx.Length.CompareTo(ty.Length);
if (result != 0)
return result;
result = tx.CompareTo(ty);
if (result != 0)
return result;
}
return string.Compare(x, y);
}
public int Compare(string? x, string? y) {
if (ReferenceEquals(x, y))
return 0;
if (x is null)
return -1;
if (y is null)
return +1;
var itemsX = Regex
.Split(x, "([0-9]+)")
.Where(item => !string.IsNullOrEmpty(item))
.ToList();
var itemsY = Regex
.Split(y, "([0-9]+)")
.Where(item => !string.IsNullOrEmpty(item))
.ToList();
for (int i = 0; i < Math.Min(itemsX.Count, itemsY.Count); ++i) {
int result = CompareChunks(itemsX[i], itemsY[i]);
if (result != 0)
return result;
}
return itemsX.Count.CompareTo(itemsY.Count);
}
}
演示:
string[] demo = new string[] {
"B01 002",
"B01 0010",
"01",
"B01 001",
"B10 001",
"B01 01",
"1",
"B1 001",
"B02 001",
"A1"
};
Array.Sort(demo, new NaturalComparer());
Console.WriteLine(string.Join(Environment.NewLine, demo));
Output:
01
1
A1
B01 001
B01 01
B01 002
B01 0010
B1 001
B02 001
B10 001
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.