c# - 我是否需要创建一个对象来按我的 "number"元素排序?

标签 c# arrays algorithm sorting

我的文件编号系统刚刚超过 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/

相关文章:

c# - 如何正确使用显式实现的接口(interface)属性和 wpf 可见性?

c - 按两个不同的值排序

javascript - 如何找到数组中第二好的?

algorithm - 智能体仅与附近智能体共享能量的高效算法?

algorithm - 迪尼克算法中的一个点

javascript - 在数据库问题中保存模式消息

c# - 在 C# 中从列表中检索最大元素索引的优雅方法

arrays - 在参数请求中传递字符串数组 - swift 5

algorithm - 为什么贪心算法对某些不同于美国货币的货币不起作用?

c# - 结构和值类型(如 C# 的)是否会包含在 Java 7 中?