我的文件编号系统刚刚超过 100,000,这导致了一些问题。也就是说,它会导致程序在 #99,999 之前组织 #100,000,因为它首先看到 1。
例如,另一个程序会像这样按升序读取文件:
XXXX_100000_XXXXXX.file
XXXX_10001_XXXXXX.file
XXXX_99999_XXXXXX.file
但它应该去:
XXXX_10001_XXXXXX.file
XXXX_99999_XXXXXX.file
XXXX_100000_XXXXXX.file
我有一个函数可以读取所有文件,按编号对它们进行排序,然后将它们按顺序放入一个新数组中。这是一些伪代码:
while(my directory has more files)
//this entire chunk assigns the number part of the filename to an int
string filename = my file
string num = filename[5] through filename[11]
//checks if the number is 5 digits, if yes, removes the underscore
if(num at position [11] == "_"){
num = num[5] through num[10]
}
int fileNum = num.toInteger
//now I have the number as an int
编辑:
我刚刚意识到,通过对文件名调用 .Split
并将 arr[1]
转换为 int
,我可以更轻松地获取数字。不过,为了好玩,我会保留旧代码。
这就是我卡住的地方。我想将它们放入一个新数组中,进行排序,或者在所有内容都放入其中后使数组可排序。
我是否需要创建一个以文件名和数字为元素的对象,将所有对象放入,然后按数字对数组进行排序?我知道这会奏效,但我忍不住想有一种更有效的方法来做到这一点。
我不需要为我编写代码,我只需要帮助制定算法逻辑,或者如果我的方法已经是最好的方法,请告诉我!
最佳答案
如果您有一个未排序的文件名数组,例如
string[] fileNames = ...
和一个从名称中提取数字的函数,例如
public static int GetFileNumber(string myfile) {
string num = filename[5] through filename[11]
//checks if the number is 5 digits, if yes, removes the underscore
if(num at position [11] == "_"){
num = num[5] through num[10]
}
return num.toInteger
}
然后您可以使用 Array.Sort
对它们进行排序:
Array.Sort(fileNames, (f1, f2) => GetFileNumber(f1).CompareTo(GetFileNumber(f2)));
关于c# - 我是否需要创建一个对象来按我的 "number"元素排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45738702/