gpt4 book ai didi

C#矩形数组排序

转载 作者:行者123 更新时间:2023-11-30 17:20:13 25 4
gpt4 key购买 nike

string[,] desc = new string[255,10];    
int descLines = 0;
cont string RDATAPATCH = "rctdata.xdb";
using (StreamReader sr = new StreamReader(RDATAPATCH))
{
descLines = 0;
while (sr.Peek() > -1)
{
sr.ReadLine();
descLines++;
}
desc = new string[descLines, 10];
int line = 0;
sr.BaseStream.Position = 0;
sr.DiscardBufferedData();
while (sr.Peek() > -1)
{
string ltxt = sr.ReadLine();
string[] lstxt = ltxt.Split('|');
for (int x = 0; x < 10; x++)
{
desc[line, x] = lstxt[x];
}
line++;
}
}
string[] sArray = new string[descLines];
for (int x = 0; x < descLines; x++)
{
sArray[x] = desc[x, 7];
}
Array.Sort(sArray);
string[,] tempDesc = new string[descLines, 10];
for (int x = 0; x < sArray.Length; x++)
{
for (int y = 0; y < desc.Length / 10; y++)
{
if (sArray[x] == desc[y, 7])
{
for (int z = 0; z < 10; z++)
{
tempDesc[x, z] = desc[y, z];
}
}
}
}
desc = tempDesc;

我有这段代码,streamreader 加载的文件是这样的:

id|rid|type|date opened|code|<0/1>|<number>|open date|availability('in stoc' or '11.11.2010'>|<0/1/2>
0|0|15fl*20ml/cut|04.2012|200905.101109|1|1|nedeschis|in stoc|2
1|0|15fl*20ml/cut|07.2012|200905.030210|1|1|nedeschis|in stoc|2
2|10|150 teste/cut|11.2012|16813A|1|3|nedeschis|in stoc|2
3|0|15fl*20ml/cut|06.2011|200905.050309|0|11|07.07.2010|in stoc|0

desc 变量按开放日期字符串排序,可以是:“nedeschis”(关闭)或“11.11.2010”(日期)。我认为我的算法是错误的任何人都可以帮助我吗?

最佳答案

该算法似乎基本上是正确的,但是由于值是按字符串排序的,因此结果不会按时间顺序排列。例如,字符串值“07.07.2010”大于“06.08.2010”。您必须将这些值转换为 DateTime 值才能正确比较它们。

此外,由于您在排序后使用日期值来标识项目,并且值不是唯一的,因此您最终会得到一些项目的重复项并丢失其他项目。仍然可以按这种方式进行排序,但是您必须在排序后删除重复的值,并更改匹配这些值的循环以处理重复的匹配项。

您可以使用字符串数组列表而不是二维数组,这样会使代码简单很多。您可以一次读取数据,并且可以对列表中的项目进行排序,而不是对特定值进行排序,然后匹配项目:

List<string[]> desc = new List<string[]>();
const string RDATAPATCH = "rctdata.xdb";
using (StreamReader sr = new StreamReader(RDATAPATCH)) {
string line;
while ((line = sr.ReadLine()) != null) {
desc.Add(line.Split('|'));
}
}
desc.RemoveAt(0); // remove field description line
desc.Sort((a, b) => {
if (a[7] == "nedeschis" && b[7] == "nedeschis") return 0;
if (a[7] == "nedeschis") return -1;
if (b[7] == "nedeschis") return 1;
return DateTime.Parse(a[7]).CompareTo(DateTime.Parse(b[7]));
});

关于C#矩形数组排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4291568/

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