替换另一个数组中的数组字段
本文关键字:数组 字段 替换 另一个 | 更新日期: 2023-09-27 17:56:30
我有一个小程序,它读取一个CSV文件,其中包含一个以逗号分隔的报告。在报表中,其中一个字段是日期,我将其转换为日期/时间,并且仅提取特定时间范围内的信息。这是我的问题:该报告实际上是在特定系统上运行的作业列表。但是,某些作业名称本身包含逗号。这意味着Excel输出报告非常混乱,因为如果作业名称具有逗号,则作业名称将在2个单元格之间划分。我对编程有点陌生,所以我能想到解决这个问题的唯一方法是检查我的数组中有多少字段由逗号分隔。如果它大于正常值,我会连接两个我知道将是工作名称的字段。但是,问题是,如果作业名称包含 2 个逗号,这将不起作用,因为它仅设置为处理数据中的 1 个额外逗号。
我应该补充一点,我读入的 CSV 报告是由另一个应用程序生成的,我无法控制它的分隔方式。否则,我会将其更改为管道或类似的东西。
有什么想法吗?下面是处理它的代码部分:
StreamReader SR = new StreamReader(inputFile);
StreamWriter SW = new StreamWriter(outputFile);
string records;
//read headers from first line
string headers = records = SR.ReadLine();
SW.WriteLine(headers);
DateTime YesterdayAM = Convert.ToDateTime(DateTime.Now.AddDays(-1).ToShortDateString() + " 05:00:00 AM");
while ((records = SR.ReadLine()) != null)
{
if (records.Trim().Length > 0)
{
string daterecord = GetDateTimeFromStringArray(records);
if (daterecord.Length > 0)
{
DateTime recordDate = Convert.ToDateTime(daterecord);
if (recordDate >= YesterdayAM)
{
string[] checkfields = records.Split(',');
if (checkfields.Length > 13)
{
string[] replacefields = { checkfields[0], checkfields[1] + " " + checkfields[2], checkfields[3], checkfields[4], checkfields[5], checkfields[6], checkfields[7], checkfields[8], checkfields[9], checkfields[10], checkfields[11], checkfields[12] };
for (int i = 0; i < replacefields.Length; i++)
{
SW.Write(replacefields[i] + ",");
}
SW.Write(Environment.NewLine);
}
else
{
SW.WriteLine(records);
}
}
}
}
}
这样做有点
麻烦,但是如果您无法修复源代码并且您知道额外的逗号只会出现在一个字段中,您可以执行以下操作:
string[] checkfields = records.Split(',');
while (checkfields.Length > 13)
{
// concat [1] & [2] into a new array
checkfields = checkfields.Take(1)
.Concat(new string[] { string.Join("", checkfields.Skip(1).Take(2).ToArray()) })
.Concat(checkfields.Skip(3)).ToArray();
} // if it's still too long it will loop again
或者更好的是:
string[] checkfields = records.Split(',');
int extraFields = checkfields.Length - 13;
if (extraFields > 0)
{
// concat fields 1....1 + extraFields
checkfields = checkfields.Take(1)
.Concat(new string[] { string.Join("", checkfields.Skip(1).Take(extraFields).ToArray()) })
.Concat(checkfields.Skip(extraFields + 1)).ToArray();
} // avoids looping by doing it all in one go
注意:linq 语句未经测试,可能不是绝对最有效的方法。此外,为了便于维护,所有"魔术"数字可能都应该替换为常量。