我有一个由base36(0-9然后是az)组织的文件夹列表.现在我读取它们的当前实现是迭代一个数字,将其转换为base32,检查文件夹是否存在.如果它没有结束,它确实读取了数据.
这里的问题是文件夹的数字有差距.例如:0,1,2,4,5,6,8,a,b,c,g,k,p
以正确的顺序迭代它们的最佳方法是什么(考虑到可以有任意数量的文件夹)?
(注意:我不能简单地获取所有目录,因为它们按字母顺序排列.例如2A将放在z之前)
我可能会将所有目录放入内存中,然后对它们进行排序,而不是尝试创建可以按顺序猜测所有可能值的内容.
var names = GetAllDirectoryNames();
names.Sort(CompareNames);
foreach( var name in Names)
{
DoSomethingWithDir(name);
}
//...
private static int CompareNames(string x, string y)
{
if( x == null && y == null) return 0;
if( x== null) return -1;
if( y == null) return 1;
var xVal = Base36Decode(x);
var yVal = Base36Decode(y);
if( xVal > yVal) return 1;
if( xVal < yVal) return -1;
return 0;
}
private long Base36Decode(string inputString)
{
var charList = "0123456789abcdefghijklmnopqrstuvwxyz";
inputString = Reverse(inputString.ToLower());
long result = 0;
int position = 0;
foreach (char c in inputString)
{
result += charList.IndexOf(c) * (long)Math.Pow(36, position);
position++;
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
这实际上是对文件夹名称进行基数排序。首先按字母顺序对它们进行排序,然后按字符串的长度进行排序。
var names = new[] {"4cc", "2a", "0", "z", "1ab"};
foreach (var n in names.OrderBy(x => x).OrderBy(y => y.Length))
{
Console.WriteLine(n);
}
Run Code Online (Sandbox Code Playgroud)
产量:
0
z
2a
1ab
4cc
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
271 次 |
| 最近记录: |