gpt4 book ai didi

c# - 匹配文件路径字符串的第一部分

转载 作者:太空宇宙 更新时间:2023-11-03 19:29:41 25 4
gpt4 key购买 nike

我有一个像下面这样的简单类:

class Record
{
public Record(string fp1, string fp2, string fp3)
{
Filepath1 = fp1;
Filepath2 = fp2;
Filepath3 = fp3;
}

public string Filepath1 { get; private set; }
public string Filepath2 { get; private set; }
public string Filepath3 { get; private set; }
}

这些文件路径中的每一个都非常相似(并且很长),并且仅在文件路径的最后几个字符方面有所不同。

现在,我希望内存中有几千条这样的记录,并且我希望这些记录占用较少的 RAM。所以我在想办法优化内存使用,这是我想出的一个解决方案:

class Record
{
private string _baseFilepath;
private string _fp1;
private string _fp2;
private string _fp3;
public Record(string fp1, string fp2, string fp3)
{
_baseFilepath = /*get common first part of filepaths*/;
_fp1 = /*last part of fp1*/;
_fp2 = /*last part of fp2*/;
_fp3 = /*last part of fp3*/;
}

public string Filepath1
{
get { return _baseFilepath + _fp1; }
}

public string Filepath2
{
get { return _baseFilepath + _fp2; }
}

public string Filepath3
{
get { return _baseFilepath + _fp3; }
}
}

您可以看到我可以节省大量 RAM,尤其是对于只有最后几个字符不同的非常长的文件路径。问题是,是否有一种简单的方法来获取文件路径的公共(public)第一部分?

编辑:内存中最多可以有700,000条Records,实际生产类的文件路径多了好几个。我正在努力让应用尽可能轻量,同时为了简单起见尽量保持优化非常简单。

最佳答案

这样就可以了:

public static string GetCommonStart(string fp1, string fp2, string fp3)
{
int idx = 0;
int minLength = Math.Min(Math.Min(fp1.Length, fp2.Length), fp3.Length);
while (idx < minLength && fp1[idx] == fp2[idx] && fp2[idx] == fp3[idx])
idx++;
return fp1.Substring(0, idx);
}

关于c# - 匹配文件路径字符串的第一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5876416/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com